namespace XenseAR
{

    using Proyecto26;
    using RSG;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using UnityEngine;

    public class BackendServices : MonoSingleton<BackendServices>
    {
        string hostURL = "https://api.xensear.cloud/api/v1";

        string authenticationUid = "";
        string authorizationUid = "";
        public void Init(string hostUrl, string authenticationUid)
        {
            if (!string.IsNullOrEmpty(hostURL))
                this.hostURL = hostUrl;
            this.authenticationUid = authenticationUid;
        }
        public void Init(string hostUrl)
        {
            if (!string.IsNullOrEmpty(hostURL))
                this.hostURL = hostUrl;
        }


        public void UpdateAuthenticationUid(string authenticationUid)
        {
            this.authenticationUid = authenticationUid;
        }

        public void UpdateAuthorizationUid(string authorizationUid)
        {
            this.authorizationUid = authorizationUid;
        }

        Dictionary<string, string> mandatoryForm = new Dictionary<string, string>();
        Dictionary<string, string> mandatoryHeader = new Dictionary<string, string>();

        public bool UpdateHeader(string key, string val)
        {
            if (key == null || val == null)
                return false;

            if (mandatoryHeader.ContainsKey(key))
                mandatoryHeader[key] = val;
            else
            {
                mandatoryHeader.Add(key, val);
            }
            Debug.Log("Update header " + key + " : " + val);

            return true;

        }

        protected override void Awake()
        {
            base.Awake();
            // for test
            //#if UNITY_EDITOR

            //        //if(UrlTransfer.Instance.lessonUrl.StartsWith("http"))
            //        //{
            //        BackendrServices.Instance.Post(new RequestHelper
            //        {
            //            SimpleForm = new Dictionary<string, string>
            //            {
            //                {"type", "GetTokenByUid" },
            //                {"uid","0" }
            //            }

            //        }).Then(response => OnReceiveToken(response.Text));
            //        // }

            //        string path = Application.persistentDataPath + "/token.json";
            //        if (File.Exists(path))
            //        {
            //            StreamReader reader = new StreamReader(path);
            //            string jsonString = reader.ReadToEnd();
            //            reader.Close();

            //            string devToken = jsonString;
            //            UpdateHeader("token", devToken);
            //        }


            //        //mandatoryHeader.Add("token", devToken);
            //#endif
        }

        public void GetAdminToken()
        {
            //string host = "master.educationxr.vn";

            //RequestHelper requestHelper = new RequestHelper
            //{
            //    SimpleForm = new Dictionary<string, string>
            //    {
            //        { "type", "GetTokenByUid" },
            //        { "uid", "0" }
            //    }
            //};

            //requestHelper.SimpleForm = requestHelper.SimpleForm == null ?
            //    mandatoryForm : mandatoryForm.Union(requestHelper.SimpleForm).ToDictionary(t => t.Key, t => t.Value);

            //requestHelper.Headers = requestHelper.Headers == null ?
            //    mandatoryHeader : mandatoryHeader.Union(requestHelper.Headers).ToDictionary(t => t.Key, t => t.Value);

            //if (String.IsNullOrEmpty(requestHelper.Uri))
            //    requestHelper.Uri = host + "/api";

            //var promise = RestClient.Post(requestHelper);
            //promise.Then(res => ReceivedToken(res, promise));



        }

        //private void ReceivedToken(ResponseHelper response, IPromise<ResponseHelper> promise)
        //{
        //    var webdata = JsonUtility.FromJson<Defines.WebResponse>(response.Text);
        //    UpdateHeader("token", webdata.data);
        //}

        //private void OnReceiveToken(string text)
        //{
        //    var webdata = JsonUtility.FromJson<Defines.WebResponse>(text);

        //    Debug.Log("devtoken" + webdata.data);
        //    string path = Application.persistentDataPath + "/token.json";
        //    System.IO.File.WriteAllText(path, webdata.data);
        //    // UpdateHeader("token", webdata.data);
        //}

        public IPromise<ResponseHelper> Post(RequestHelper requestHelper)
        {
            requestHelper.SimpleForm = requestHelper.SimpleForm == null ?
                mandatoryForm : mandatoryForm.Union(requestHelper.SimpleForm).ToDictionary(t => t.Key, t => t.Value);

            requestHelper.Headers = requestHelper.Headers == null ?
                mandatoryHeader : mandatoryHeader.Union(requestHelper.Headers).ToDictionary(t => t.Key, t => t.Value);

            if (String.IsNullOrEmpty(requestHelper.Uri))
                requestHelper.Uri = hostURL;

            //Debug.Log("Post");
            //Debug.Log(requestHelper.Headers["token"]);
            //Debug.Log(requestHelper.Uri);
            requestHelper.Headers["Authorization"] = authenticationUid;
            requestHelper.SimpleForm.Add("uid", authorizationUid);
#if !UNITY_EDITOR
        requestHelper.SimpleForm.Add("state", "viewer");
#else
            requestHelper.SimpleForm.Add("state", "editor");
#endif

            Debug.Log("Post " + requestHelper.Uri);
            var promise = RestClient.Post(requestHelper);
            promise.Then(res => ValidateResponse(res, promise));
            return promise;
        }

        public IPromise<ResponseHelper> Put(RequestHelper requestHelper)
        {
            requestHelper.SimpleForm = requestHelper.SimpleForm == null ?
                mandatoryForm : mandatoryForm.Union(requestHelper.SimpleForm).ToDictionary(t => t.Key, t => t.Value);

            requestHelper.Headers = requestHelper.Headers == null ?
                mandatoryHeader : mandatoryHeader.Union(requestHelper.Headers).ToDictionary(t => t.Key, t => t.Value);

            if (String.IsNullOrEmpty(requestHelper.Uri))
                requestHelper.Uri = hostURL;

            //Debug.Log("Post");
            //Debug.Log(requestHelper.Headers["token"]);
            //Debug.Log(requestHelper.Uri);

#if !UNITY_EDITOR
        requestHelper.SimpleForm.Add("state", "viewer");
#else
            requestHelper.SimpleForm.Add("state", "editor");
#endif

            Debug.Log("Post " + requestHelper.Uri);
            var promise = RestClient.Put(requestHelper);
            promise.Then(res => ValidateResponse(res, promise));
            return promise;
        }

        public IPromise<ResponseHelper> Get(RequestHelper requestHelper)
        {

            return RestClient.Get(requestHelper);
        }

        private IPromise<ResponseHelper> ValidateResponse(ResponseHelper response, IPromise<ResponseHelper> promise)
        {
            // Debug.Log("On validate request response");
            if (response.StatusCode != Defines.successCode)
            {
                Debug.Log("Validate fail with code: " + response.StatusCode);
                return promise;
            }
            return promise;
        }

        public IPromise<ResponseHelper> Upload(RequestHelper requestHelper, string fileName, Dictionary<string, string> fields = null, string dataKey = null, bool overwrite = false)
        {
            WWWForm uploadForm = new WWWForm();
            if (dataKey != null)
            {
                uploadForm.AddBinaryData(dataKey, requestHelper.BodyRaw, fileName);
            }
            else
            {
                uploadForm.AddBinaryData("educationxrfile", requestHelper.BodyRaw, fileName);
            }
            uploadForm.AddField("overwrite", overwrite.ToString());
            if (fields != null)
            {
                foreach (var field in fields)
                {
                    uploadForm.AddField(field.Key, field.Value);
                }
            }

            requestHelper.BodyRaw = null;
            foreach (var pair in mandatoryForm)
            {
                uploadForm.AddField(pair.Key, pair.Value);
            }

            //foreach (var pair in mandatoryHeader)
            //{
            //    uploadForm.headers.Add(pair.Key, pair.Value);
            //}
            requestHelper.FormData = uploadForm;
            requestHelper.Headers = requestHelper.Headers == null ?
                mandatoryHeader : mandatoryHeader.Union(requestHelper.Headers).ToDictionary(t => t.Key, t => t.Value);

            if (String.IsNullOrEmpty(requestHelper.Uri))
                requestHelper.Uri = hostURL + "/updatefile";
            return RestClient.Post(requestHelper);
        }


    }
}
