﻿using System;
using UnityEngine;
using UnityEngine.UI;
using ZenFulcrum.EmbeddedBrowser;

public class LTSdkWebview
{
    // webview zoom
    private float mWebviewZoom = 0;

    private string mUrl = "";
    
    // Use this for initialization
    Browser    browser;
    GameObject closebtnObj;
    //GameObject myCanvas;
    GameObject instance;
    public LTSdkWebview()
    {
        //获取插件Browser组件（Unity方使用插件基础一步）
        //browser = gameObject.GetComponent<Browser>();
        mWebviewZoom = 0;
        GameObject myCanvas = GameObject.Find("Canvas");
        instance = GameObject.Instantiate(Resources.Load("Browser (GUI)")) as GameObject;
        instance.transform.SetParent(myCanvas.transform, false);//再将它设为canvas的子物体
        //LTBaseDataCollector.GetInstance().PreviousObj = instance;
        browser = instance.GetComponent<Browser>();

        closebtnObj = instance.transform.Find("UINavigationBar/CloseButton").gameObject;

        var closeBtn = closebtnObj.GetComponent<Button>();
        if (closeBtn)
        {
            closeBtn.onClick.AddListener(delegate () {
                this.CloseWebview();
            });
        }

        //browser.onLoad += Browser_onLoad;
        browser.onFetchError += Browser_FetchError;
        browser.onNavStateChange += () =>
        {
            browser.Zoom = mWebviewZoom;
            string url = browser.Url;
            Debug.Log("onNavStateChange url == " + url);
        };

        //browser.onBrowserFocus += (a,b) => {
        //    if (a)
        //    {
        //        GoBack();
        //    }
        //    if (b) {
        //        GoBack();
        //    }
        //};
        //browser.onNavStateChange += () => {
        //    if (Input.GetKey(KeyCode.Escape))
        //    {
        //        //but only if it's not focused (don't steal kill something the user is typing)
        //        //urlInput.text = browser.Url;
        //        browser.GoBack();
        //    }
        //};
    }
    
    public void ShowWebView(string url, object param = null, Action action = null)
    {
        mUrl                 =  url;
        browser.Url          =  url;
        browser.WhenLoaded(() => { });
        browser.Zoom         =  mWebviewZoom;
    }
    
    public void CloseWebview()
    {
        GameObject.Destroy(instance);
    }

    /// <summary>
    /// 页面打开失败处理
    /// </summary>
    /// <param name="obj"></param>
    private void Browser_FetchError(JSONNode obj)
    {
        Debug.LogError(" LTSdkWebview Browser_FetchError  obj == " + obj.AsJSON);
    }
}

