using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace XenseAR {
    public class TestingPresetManager : MonoBehaviour
    {
        [SerializeField] TestingPresetObject TestingPreset;
        [SerializeField] AppSettingObject AppSetting;

        [SerializeField] TMP_Dropdown homescreenUrlDropdown;
        [SerializeField] TMP_Dropdown homescreenUrlFromAPIDropdown;
        [SerializeField] Button StartTestingButton;

        [SerializeField] TMP_Text message;
        [SerializeField] TMP_Text homescreenUrlPreview;

        [SerializeField] TMP_Text buildCommit;

        [SerializeField] TMP_Text clearCacheResponse;

        public XenseConfigURL selectedConfigURL;
        private WebSettingsResponse settings;

        public class WebSetting
        {
            public string Title { get; set; }
            public string Frontend { get; set; }
            public string Backend { get; set; }
            public string Kibana { get; set; }
        }

        public class WebSettingsResponse
        {
            public int Status { get; set; }
            public string Message { get; set; }
            public List<WebSetting> Data { get; set; }
        }

        // Start is called before the first frame update
        void Start()
        {
            homescreenUrlDropdown.value = 0;
            TestingPreset.finalURL.Update(TestingPreset.awsURL);
            selectedConfigURL = TestingPreset.finalURL;

            buildCommit.text = TestingPreset.BuildCommit;
            homescreenUrlPreview.text = TestingPreset.finalURL.homeURL;
            homescreenUrlDropdown.onValueChanged.AddListener(OnHomescreenUrlChanged);
            StartTestingButton.onClick.AddListener(OnStartTestingButtonClicked);
            homescreenUrlFromAPIDropdown.onValueChanged.AddListener(OnHomescreenUrlFromAPIChanged);

            homescreenUrlFromAPIDropdown.transform.parent.gameObject.SetActive(false);
            selectedConfigURL = new XenseConfigURL();
            string url = "https://xensear.vn/api/v1";
            string bodyString = "{\"type\":\"GetAppWebSettings\"}";
            StartCoroutine(PostRawJson(bodyString, url, OnWebUrlReceived));
        }

        private void OnWebUrlReceived(string response)
        {
            settings = JsonConvert.DeserializeObject<WebSettingsResponse>(response);
            homescreenUrlFromAPIDropdown.ClearOptions();

            List<string> titles = new List<string>();
            foreach (var setting in settings.Data)
            {
                titles.Add(setting.Title);
            }
            homescreenUrlFromAPIDropdown.AddOptions(titles);
            homescreenUrlFromAPIDropdown.transform.parent.gameObject.SetActive(true);
            if(settings.Data.Count > 0)
            {
                homescreenUrlFromAPIDropdown.value = 0;
                selectedConfigURL.homeURL = settings.Data[0].Frontend;
                selectedConfigURL.backendURL = settings.Data[0].Backend;
                selectedConfigURL.analysisURL = settings.Data[0].Kibana;
            } else
            {
                clearCacheResponse.text = "Web settings is empty";
            }

        }

        private void OnStartTestingButtonClicked()
        {
            try
            {
                if (!string.IsNullOrEmpty(selectedConfigURL.homeURL))
                {
                    message.text = "Ready for testing!";
                    message.color = Color.green;
                    AppSetting.XenseUrl.Update(selectedConfigURL);
                    SceneManager.LoadScene("SplashScene", LoadSceneMode.Single);
                }
                else
                {
                    message.text = "HomescreenUrl is empty, please check build or try reselect from dropdown!";
                    message.color = Color.red;
                }
            }
            catch (Exception e)
            {
                message.text = "Something went wrong!!!";
                message.color = Color.red;
            }

        }

        private void OnHomescreenUrlFromAPIChanged(int index)
        {
            foreach (var setting in settings.Data)
            {
                if(homescreenUrlFromAPIDropdown.options[index].text.Equals(setting.Title))
                {
                    selectedConfigURL.homeURL = setting.Frontend;
                    selectedConfigURL.backendURL = setting.Backend;
                    selectedConfigURL.analysisURL = setting.Kibana;
                    break;
                }
            }
            
            homescreenUrlPreview.text = selectedConfigURL.backendURL + "\n" + selectedConfigURL.analysisURL + "\n" + selectedConfigURL.homeURL;
        }

        private void OnHomescreenUrlChanged(int index)
        {
            switch (homescreenUrlDropdown.options[index].text)
            {
                case "Prod":
                    TestingPreset.finalURL.Update(TestingPreset.prodURL);
                    break;
                case "Dev":
                    TestingPreset.finalURL.Update(TestingPreset.devURL);
                    break;
                case "AWS":
                    TestingPreset.finalURL.Update(TestingPreset.awsURL);
                    break;
                case "Sun":
                    TestingPreset.finalURL.Update(TestingPreset.sunURL);
                    break;
                default:
                    TestingPreset.finalURL.Update(TestingPreset.prodURL);
                    break;
            }
            selectedConfigURL = TestingPreset.finalURL;
            homescreenUrlPreview.text = TestingPreset.finalURL.backendURL + "\n" + TestingPreset.finalURL.analysisURL + "\n" + TestingPreset.finalURL.homeURL;
        }

        private void OnDestroy()
        {
            homescreenUrlDropdown.onValueChanged.RemoveListener(OnHomescreenUrlChanged);
            homescreenUrlFromAPIDropdown.onValueChanged.RemoveListener(OnHomescreenUrlFromAPIChanged);
        }


        public void ClearCloudCache()
        {
            string url = "https://xensear.vn/api/cache";
            string bodyString = "{\"type\":\"InvalidateCache\",\"scope\":\"arworld-cache\"}";
            StartCoroutine(PostRawJson(bodyString, url));
        }

        public void ClearCloudCounter()
        {
            string url = "https://xensear.vn/api/cache";
            string bodyString = "{\"type\":\"InvalidateCache\",\"scope\":\"arworld-counter\"}";
            StartCoroutine(PostRawJson(bodyString, url));
        }

        private IEnumerator PostRawJson(string jsonString, string url, Action<string> handleResponse = null)
        {
            clearCacheResponse.text = "Send request...";

            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);

            UnityWebRequest request = new UnityWebRequest(url, "POST");
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                clearCacheResponse.text = "Please wait...";
                yield return new WaitForSeconds(5f);
                clearCacheResponse.text = "success: " + request.downloadHandler.text;
                handleResponse?.Invoke(request.downloadHandler.text);
                Debug.Log("Response: " + request.downloadHandler.text);
            }
            else
            {
                yield return new WaitForSeconds(5f);
                clearCacheResponse.text = "false: " + request.downloadHandler.text;
                Debug.LogError("POST failed: " + request.error);
            }
        }

    }
}
