package com.cygnusa.hyperm.fragments;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.cygnusa.hyperm.LoginActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.wrappers.FragmentItem;

import java.util.ArrayList;
import java.util.Objects;

public class AMSalesFragment extends Fragment {


    String url;
    View mainView;
    TransparentProgressDialog progressDialog;
    ApiService restService;

    ArrayList<FragmentItem> fragments = new ArrayList<>();
    WebView mWebView;
    private boolean canGoLogin = true;

    public AMSalesFragment() {

    }

    public void onResumeFragment(String urlString) {
        url = GlobalData.REPORT_URL + urlString + GlobalData.user.getAccess_token();

        if (mWebView != null) {
            mWebView.loadUrl("about:blank");
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mWebView.clearCache(true);
                mWebView.clearHistory();
                mWebView.loadUrl(url);
            }
        }, 500);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.am_sales, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        mWebView = mainView.findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.getSettings().setUserAgentString("Android");
        mWebView.getSettings().setUserAgentString("Chrome");
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.requestFocus(View.FOCUS_DOWN);
        mWebView.getSettings().setGeolocationEnabled(true);

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap icon) {
                super.onPageStarted(view, url, icon);
                if (url.equalsIgnoreCase(GlobalData.REPORT_URL)) {
                    if (canGoLogin) {
                        canGoLogin = false;
                        Objects.requireNonNull(getActivity()).getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                .edit().putString("FCM_TOKEN_ID", "").apply();
                        GlobalData.sdb.delete("session", null, null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        Objects.requireNonNull(getActivity()).finish();
                    }
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.equalsIgnoreCase(GlobalData.REPORT_URL)) {
                    if (canGoLogin) {
                        canGoLogin = false;
                        Objects.requireNonNull(getActivity()).getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                .edit().putString("FCM_TOKEN_ID", "").apply();
                        GlobalData.sdb.delete("session", null, null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        Objects.requireNonNull(getActivity()).finish();
                    }
                }
            }
        });

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDescription,
                                        String mimetype, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(
                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                String fileName = URLUtil.guessFileName(url, contentDescription, mimetype);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
                DownloadManager dManager = (DownloadManager) Objects.requireNonNull(getActivity()).getSystemService(Context.DOWNLOAD_SERVICE);
                Objects.requireNonNull(dManager).enqueue(request);
            }
        });

    }

    public void showHelpScreen() {

    }
}
