package com.app.simplitend.articles;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.app.simplitend.databinding.ActivityArticleShowerBinding;

public class ArticleShowerActivity extends AppCompatActivity {

    protected ActivityArticleShowerBinding binding;

    private String url, title;

    public static final String ARTICLE_URL_KEY = "article_url";
    public static final String ARTICLE_TITLE = "article_title";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityArticleShowerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initViews();

        clickEvents();

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private void initViews() {

        Intent intent = getIntent();
        if (intent != null){
            url = intent.getStringExtra(ARTICLE_URL_KEY);
            title = intent.getStringExtra(ARTICLE_TITLE);
            if (title != null){
                binding.toolbar.setTitle(title);
            }

            loadUrl();
        }
    }

    private void loadUrl() {
        if (url == null){
            Toast.makeText(this, "Couldn't load the article.", Toast.LENGTH_SHORT).show();
            return;
        }

        binding.progressBar.setVisibility(View.VISIBLE);

        binding.webView.getSettings().setJavaScriptEnabled(true);
        binding.webView.getSettings().setBuiltInZoomControls(true);
        binding.webView.getSettings().setDisplayZoomControls(false);

        binding.webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
                binding.progressBar.setVisibility(View.GONE);
            }
        });

        binding.webView.loadUrl(url);
    }

    private void clickEvents() {
        binding.toolbar.setNavigationOnClickListener(v -> {
            onBackPressed();
        });
    }
}