package com.cpm.lorealbaMabeline.dailyactivity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gsonGetterSetter.JourneyPlan;

import java.util.Objects;

import im.delight.android.webview.AdvancedWebView;


public class BaAssessmentActivity extends AppCompatActivity {
    private final Handler loaderHandler = new Handler(Looper.getMainLooper());
    private String username;
    private String couter_code;
    private Lorealba_Database db;
    JourneyPlan jcp_Object = new JourneyPlan();
    AdvancedWebView webView;
    ProgressBar progressBar;
    private Runnable showLoaderRunnable;
    private boolean pageLoaded = false;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ba_assessment);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        webView = (AdvancedWebView) findViewById(R.id.webviewbaAssessment);
        SharedPreferences preferences = PrefHelper.getPrefs(this);
        String date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        String counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(this)) {
            toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile);
        }
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        db = new Lorealba_Database(this);
        db.open();
        jcp_Object = db.getBIDfromJCP(username, counter_id);
        setTitle("BA Assessment - " + date);

        if (CommonFunctions.checkNetIsAvailable(this)) {
            loadWeb();
        } else {
            AlertandMessages.showToastMsg(this, getString(R.string.nonetwork));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
            this.finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void loadWeb() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        // Android 5+ mixed content
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webView.loadUrl(CommonString.BA_ASSESSMENT_URL + "c=" + couter_code + "&u=" + username);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                pageLoaded = false;

                showLoaderRunnable = () -> {
                    if (!pageLoaded) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                };

                // ⏳ Wait 400ms before showing loader
                loaderHandler.postDelayed(showLoaderRunnable, 4000);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                pageLoaded = true;

                loaderHandler.removeCallbacks(showLoaderRunnable);
                progressBar.setVisibility(View.GONE);
            }
        });

    }
}
