package com.nsgk.ruralWeb;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.WebBackForwardList;
import android.webkit.WebHistoryItem;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.nsgk.ruralWeb.sys.NSConstants;
import com.nsgk.ruralWeb.sys.NSPreference;
import com.nsgk.ruralWeb.utils.NSContextUtils;
import com.nsgk.ruralWeb.utils.NSStr;
import com.nsgk.ruralWeb.web.NSEnvWindowObject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import cn.hutool.core.util.StrUtil;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends AppCompatActivity {
    private static final String ID_TAG = FullscreenActivity.class.getName();
    public static final int PERMISSION_LOCATION_REQUEST_CODE = 0x1001;


    private AgentWeb mAgentWeb;
    private NSPreference preference;
    private NSEnvWindowObject envWindowObject;

    private String m_lastUrl;
    private String m_mainUrl;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);
        String appHomeUrl = GetHomeUrl();
        //appHomeUrl = "http://192.168.0.250:85/sunVillage_info/login";
        Log.i(ID_TAG, "App home url: " + appHomeUrl);
//        init();
        AgentWeb.PreAgentWeb builder = AgentWeb.with(this)//
                .setAgentWebParent(findViewById(R.id.ll), -1, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))//传入AgentWeb的父控件。
                .useDefaultIndicator(-1, 3)//设置进度条颜色与高度，-1为默认值，高度为2，单位为dp。
                .setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onProgressChanged(WebView view, int newProgress)
                    {
                        super.onProgressChanged(view, newProgress);
                        if(newProgress != 100)
                            return;
                        String url = view.getUrl();
                        if(IsInDefaultPage())
                        {
                            m_mainUrl = url;
                            DumpMainUrl(url);
                            Log.i(ID_TAG, "设定主页地址: " + m_mainUrl);
                        }
                        else if(IsDefaultPage(url))
                        {
                            m_mainUrl = null;
                            Log.i(ID_TAG, "清空主页地址");
                        }
                        m_lastUrl = url;
                    }
                })
                .setWebViewClient(new WebViewClient() {
                })//WebViewClient ， 与 WebView 使用一致 ，但是请勿获取WebView调用setWebViewClient(xx)方法了,会覆盖AgentWeb DefaultWebClient,同时相应的中间件也会失效。
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //严格模式 Android 4.2.2 以下会放弃注入对象 ，使用AgentWebView没影响。
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他页面时，弹窗质询用户前往其他应用 AgentWeb 3.0.0 加入。
                .interceptUnkownUrl() //拦截找不到相关页面的Url AgentWeb 3.0.0 加入。
                .createAgentWeb()//创建AgentWeb。
                .ready()//设置 WebSettings。
        ;

        boolean openDef = IsDefaultPage(appHomeUrl);

        if(!openDef)
        {
            Log.i(ID_TAG, "载入主页: " + appHomeUrl);
            RestoreCookie(); // 重载cookie
            m_mainUrl = appHomeUrl;
        }
        else
        {
            Log.i(ID_TAG, "载入登录页");
            GetPreference().Remove(NSPreference.COOKIES); // Remove cookies
        }

        mAgentWeb = builder.go(appHomeUrl); //WebView载入该url地址的页面并显示。

        int fontScale = GetPreference().GetInt(NSPreference.FONT_SCALE);
        Log.i(ID_TAG, "全局字体缩放: " + fontScale + "%");
        if(fontScale > 0 && fontScale != 100)
            GetWebView().getSettings().setTextZoom(fontScale);

        // 注入宿主对象
        envWindowObject = new NSEnvWindowObject(this, new Handler(), GetWebView());
        mAgentWeb.getJsInterfaceHolder().addJavaObject("_Native_object", envWindowObject);

               /*  上边url是各个APP项目的入口地址
               事项审批 http://116.255.223.226:82/yinnongLogin    图标 ic_launcher_sxsp 或者 ic_launcher_yhzl
               阳光村务（村级事项） http://116.255.223.226:82/sunVillage_info/login  图标 ic_launcher_ygcw
               大托管 http://218.59.175.43:96/agriculturalTrusteeship/index   图标 ic_launcher_dtg
               产权交易 http://116.255.223.226:82/index  图标 ic_launcher_cqjy
               农业执法 http://116.255.223.226:82/lawEnforcement/login  图标 ic_launcher_nyzf
               宅基地审批（乌市版） https://36.134.89.93:82/zjdLogin 图标 ic_launcher_zjd
               宅基地调查 http://116.255.223.226:82/homesteadLogin  图标 ic_launcher_zjddc
               两清三化 http://116.255.223.226:89/homestead/login   图标 ic_launcher_2q3h
               网上家园（废） http://116.255.223.226:82/onlineHomeLogin   图标 ic_launcher_white
               确权调查 http://116.255.223.226:82/contracted/login   图标 ic_launcher_qqdc
               一体机 http://47.98.113.57:81   图标 ic_launcher_njytj
               */

        Log.d(ID_TAG, "UI线程: " + Thread.currentThread().getId());
    }

    @Override
    protected void onPause() {
        if(IsRecordUrl())
        {
            DumpCookie();
        }
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if(!IsRecordUrl())
        {
            Log.d(ID_TAG, "Remove url and cookie record");
            GetPreference().Remove(NSPreference.COOKIES);
            GetPreference().Remove(NSPreference.LAST_ACCESS_URL);
        }
        mAgentWeb.getWebLifeCycle().onDestroy();
        envWindowObject.OnDestroy();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
//            mWebView.goBack();
//            return true;
//        }
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_LOCATION_REQUEST_CODE) {
            int granted = 0;
            for(int i = 0; i < permissions.length; i++)
            {
                boolean b = grantResults[i] == PackageManager.PERMISSION_GRANTED;
                Log.i(ID_TAG, String.format("请求权限: %s -> %s", permissions[i], b ? "通过" : "拒绝"));
                if(b)
                    granted++;
            }
            if (granted < permissions.length) {
                Toast.makeText(this, "需要定位权限", Toast.LENGTH_LONG).show();
                NSContextUtils.RequestLocationPermission(this, FullscreenActivity.PERMISSION_LOCATION_REQUEST_CODE);
            }
        }
    }

    @Override
    public void onBackPressed()
    {
        WebView webView = GetWebView();
        if (null != webView && !webView.canGoBack() && !IsInDefaultPage()) {
            webView.loadUrl(NSConstants.AppHomeUrl());
            webView.clearHistory();
            //History();
            return;
        }
        super.onBackPressed();
    }

    private NSPreference GetPreference()
    {
        if(null == preference)
            preference = new NSPreference(this);
        return preference;
    }

    private boolean IsRecordUrl()
    {
        return GetPreference().GetBool(NSPreference.OPEN_LAST_URL);
    }

    private String GetHomeUrl()
    {
        String url = null;
        if(IsRecordUrl())
            url = GetPreference().GetString(NSPreference.LAST_ACCESS_URL, NSConstants.AppHomeUrl());
        if(StrUtil.isBlank(url))
            url = NSConstants.AppHomeUrl();
        return url;
    }

    private WebView GetWebView()
    {
        return mAgentWeb.getWebCreator().getWebView();
    }

    private void DumpMainUrl(String url)
    {
        if(StrUtil.isNotEmpty(url))
            GetPreference().SetString(NSPreference.LAST_ACCESS_URL, url);
        else
            GetPreference().Remove(NSPreference.LAST_ACCESS_URL);
        Log.d(ID_TAG, "Dump URL: " + url);
    }

    private void DumpCookie()
    {
        String url = NSStr.GetUrlPart(NSConstants.AppHomeUrl());
        String cookies = AgentWebConfig.getCookiesByUrl(url);
        GetPreference().SetString(NSPreference.COOKIES, cookies);
        Log.d(ID_TAG, "Dump cookie: " + "url=" + url + ", cookie=" + cookies);
    }

    private void RestoreCookie()
    {
        String cookies = GetPreference().GetString(NSPreference.COOKIES);
        if(StrUtil.isNotBlank(cookies))
        {
            String url = NSStr.GetUrlPart(NSConstants.AppHomeUrl());
            AgentWebConfig.syncCookie(url, cookies);
            Log.d(ID_TAG, "Restore cookie: " + "url=" + url + ", cookie=" + cookies);
        }
    }

    private boolean IsInDefaultPage()
    {
        return IsDefaultPage(m_lastUrl);
    }

    private boolean IsDefaultPage(String url)
    {
        return NSConstants.AppHomeUrl().equals(url);
    }

    private void History()
    {
        WebBackForwardList webBackForwardList = GetWebView().copyBackForwardList();
        for(int i = 0; i < webBackForwardList.getSize(); i++)
        {
            WebHistoryItem item = webBackForwardList.getItemAtIndex(i);
            Log.d(ID_TAG, StrUtil.format("{}: {} {}", i, item.getTitle(), item.getUrl()));
        }
    }
}