using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SmartBowSDK
{
    public class SmartBowNetwork : MonoBehaviour
    {
        public SmartBowHelper smartBowHelper;

        private const string serverURL = "https://xmjssvr.cn/SmartBowBusinessServer";
        //private const string serverURL = "http://127.0.0.1:11332/SmartBowBusinessServer";

        private string loginToken;
        public void Login(string gameID, string channelID, string username, string password, Action<LoginResult> callback)
        {
            WWWForm form = new WWWForm();
            form.AddField("gameID", gameID);
            form.AddField("channelID", channelID);
            form.AddField("username", username);
            form.AddField("password", password);
            StartCoroutine(Post(serverURL + "/SmartBowSDK/login", form, (res) =>
            {
                bool loginSuccess = res.code == 0;
                if (loginSuccess) loginToken = res.data as string;
                LoginResult loginResult = new LoginResult();
                loginResult.success = loginSuccess;
                loginResult.message = res.msg;
                callback?.Invoke(loginResult);
            }));
        }

        public void Logout(Action<bool> callback)
        {
            loginToken = null;
            callback?.Invoke(true);
        }

        public void GetUserInfo(Action<GetUserInfoResult> callback)
        {
            GetUserInfoResult getUserInfoResult = new GetUserInfoResult();
            if (loginToken == null)
            {
                getUserInfoResult.message = "尚未登录";
                callback?.Invoke(getUserInfoResult);
                return;
            }
            WWWForm form = new WWWForm();
            form.AddField("token", loginToken);
            StartCoroutine(Post(serverURL + "/SmartBowSDK/getUserInfo", form, (res) =>
            {
                if (res.code == 0)
                {
                    UserInfo userInfo = (res.data as JObject).ToObject<UserInfo>();
                    getUserInfoResult.success = true;
                    getUserInfoResult.userInfo = userInfo;
                }
                getUserInfoResult.message = res.msg;
                callback?.Invoke(getUserInfoResult);
            }));
        }

        private string GetCalibrateDataStorageLocalKey(string mac)
        {
            string key = "CalibrateDataStorage";
            string version = "1.0.0";
            return key + "_" + mac + "_" + version;
        }

        internal void SaveCalibrateRecord(string mac, string record)
        {
            if (smartBowHelper.calibrateDataStorageMode == CalibrateDataStorageMode.Local)
            {
                PlayerPrefs.SetString(GetCalibrateDataStorageLocalKey(mac), record == null ? "" : record);
            }
            else if (smartBowHelper.calibrateDataStorageMode == CalibrateDataStorageMode.Remote)
            {
                WWWForm form = new WWWForm();
                form.AddField("mac", mac);
                form.AddField("record", record);
                StartCoroutine(Post(serverURL + "/SmartBowSDK/saveCalibrateRecord", form, null));
            }
        }

        internal void GetCalibrateRecord(string mac, Action<string> callback)
        {
            if (smartBowHelper.calibrateDataStorageMode == CalibrateDataStorageMode.Local)
            {
                callback?.Invoke(PlayerPrefs.GetString(GetCalibrateDataStorageLocalKey(mac), ""));
            }
            else if (smartBowHelper.calibrateDataStorageMode == CalibrateDataStorageMode.Remote)
            {
                WWWForm form = new WWWForm();
                form.AddField("mac", mac);
                StartCoroutine(Post(serverURL + "/SmartBowSDK/getCalibrateRecord", form, (res) =>
                {
                    if (res.code == 0) callback?.Invoke(res.data as string);
                }));
            }
        }

        public static IEnumerator Post(string url, WWWForm form, Action<RequestResult> callback)
        {
            using (UnityWebRequest request = UnityWebRequest.Post(url, form))
            {
                yield return request.SendWebRequest();
                if (request.result == UnityWebRequest.Result.Success)
                    callback?.Invoke(JsonConvert.DeserializeObject<RequestResult>(request.downloadHandler.text));
                else
                    callback?.Invoke(new RequestResult());
            }
        }

        public static IEnumerator LoadSprite(string url, Action<Sprite> callback)
        {
            using (UnityWebRequest uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET))
            {
                uwr.downloadHandler = new DownloadHandlerTexture();
                yield return uwr.SendWebRequest();
                if (uwr.result != UnityWebRequest.Result.Success) yield break;
                Texture2D texture = DownloadHandlerTexture.GetContent(uwr);
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                callback?.Invoke(sprite);
            }
        }
    }

    public class RequestResult
    {
        public int code = -9999;
        public object data;
        public string msg = "网络出错";
    }

    public class LoginResult
    {
        /// <summary>
        /// 是否登录成功
        /// </summary>
        public bool success;
        /// <summary>
        /// 消息描述
        /// </summary>
        public string message;
    }

    public class GetUserInfoResult
    {
        /// <summary>
        /// 是否获取成功
        /// </summary>
        public bool success;
        /// <summary>
        /// 消息描述
        /// </summary>
        public string message;
        /// <summary>
        /// 用户信息
        /// </summary>
        public UserInfo userInfo;
    }

    public class UserInfo
    {
        /// <summary>
        /// 昵称
        /// </summary>
        public string nickname;
        /// <summary>
        /// 头像地址
        /// </summary>
        public string avatarUrl;
        /// <summary>
        /// 性别（1表示男，2表示女）
        /// </summary>
        public int gender;
    }
}
