#if UNITY_STANDALONE
using System;
using System.Collections.Generic;
using System.Linq;
using _Core;
using Seayoo.ComboSDK.Windows;

namespace _Combo
{
    internal class RedeemGiftCodeManager : Singleton<RedeemGiftCodeManager>
    {
        private string giftCodeUrl = "";
        private Action<ComboResult<RedeemGiftCodeResult>> redeemGiftCodeResult;

        public void Setup()
        {
            EventSystem.Register(this);
            this.giftCodeUrl = GlobalParameters.Instance.GameGiftCodeUrl;
        }

        public void RedeemGiftCode(RedeemGiftCodeOptions opts, Action<ComboResult<RedeemGiftCodeResult>> action)
        {
            redeemGiftCodeResult = action;
            if(!IdPManager.Instance.GetUser().IsLogin())
            {
                var error = new InternalError(I18n.T("login_required_error"));
                redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateFail(error));
                return;
            }
            if(opts.GitfCode != null && opts.GitfCode != "")
            {
                var identityToken = IdPManager.Instance.GetUser().identityToken;
                UIController.Instance.ShowLoading(0.5f);
                ComboClient.RedeemGiftCode(identityToken, opts.GitfCode, opts.ServerId, opts.RoleId, opts.RoleName, result =>{
                    if(result.IsSuccess)
                    {
                        UIController.Instance.HideLoading();
                        redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateSuccess(new RedeemGiftCodeResult()));
                        Log.I("RedeemGiftCode success");
                    }
                }, (err) => {
                    UIController.Instance.HideLoading();
                    redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateFail(err));
                });
                return;
            }
            if(string.IsNullOrEmpty(giftCodeUrl))
            {
                UIController.Instance.HideLoading();
                var invalidArgumentsError = new InvalidArgumentsError("giftCode", errorType : InvalidArgumentsErrorType.INVALID_GIFT_CODE_URL);
                var error = new InternalError(I18n.T("gift_code_url_error"), invalidArgumentsError);
                redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateFail(error));
                return;
            }

            CreateGiftCodeTicket(opts, ticket =>{
                try
                {
                    var url = GetUrl(ticket, opts);
                    Log.I("giftCode url: " + url);
                    UIController.Instance.ShowWebView(url, WebViewType.GiftCode, opts.Width, opts.Height, false);
                }
                catch(InternalError error)
                {
                    UIController.Instance.HideLoading();
                    redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateFail(error));
                }
            });
        }

        private void CreateGiftCodeTicket(RedeemGiftCodeOptions opts, Action<string> callback)
        {
            var identityToken = IdPManager.Instance.GetUser().identityToken;

            UIController.Instance.ShowLoading(0.5f);
            ComboClient.CreateGiftCodeTicket(identityToken, opts.ServerId, opts.RoleId, opts.RoleName, result =>{
                if(result.IsSuccess)
                {
                    var ticket = result.Data.ticket;
                    Log.I("CreateGiftCodeTicket success: " + ticket);
                    callback(ticket);
                }
            }, (err) => {
                UIController.Instance.HideLoading();
                redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateFail(err));
            });
        }

        [EventSystem.BindEvent]
        public void LoadRedeemGiftCodeFailed(LoadFailed evt)
        {
            if(evt.webViewType != WebViewType.GiftCode)
            {
                return;
            }
            var error = new InternalError(I18n.T("gift_code_open_error"));
            redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateFail(error));
        }

        [EventSystem.BindEvent]
        public void LoadRedeemGiftCodeSuccess(LoadSuccess evt)
        {
            if(evt.webViewType != WebViewType.GiftCode)
            {
                return;
            }
            redeemGiftCodeResult?.Invoke(ComboResult<RedeemGiftCodeResult>.CreateSuccess(new RedeemGiftCodeResult()));
        }

        private string GetUrl(string ticket, RedeemGiftCodeOptions opts)
        { 
            var queryParameters = new Dictionary<string, string>
            {
                { "ticket", ticket },
                { "lang", I18n.GetLanguageCode()}
            };
            string queryParametersStr = string.Join("&", queryParameters.Select(kv => $"{kv.Key}={kv.Value}"));
            return $"{giftCodeUrl}?{queryParametersStr}";
        }
    }
}
#endif