using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using static System.Net.Mime.MediaTypeNames;

namespace ET.Client
{
	[FriendOf(typeof(UIAlertComponent))]
	public static class UIAlertComponentSystem
    {
		[ObjectSystem]
		public class UIAlertComponentAwakeSystem : AwakeSystem<UIAlertComponent>
		{
			protected override void Awake(UIAlertComponent self, params object[] param)
			{
                ReferenceCollector rc = self.GetParent<UI>().GameObject.GetComponent<ReferenceCollector>();
                self.cancelTxt = rc.Get<GameObject>("cancelTxt");
                self.sureTxt = rc.Get<GameObject>("sureTxt");
                self.contentTxt = rc.Get<GameObject>("contentTxt");
                self.titleTxt = rc.Get<GameObject>("titleTxt");
                self.cancelBtn = rc.Get<GameObject>("cancelBtn");
                self.cancelBtn.GetComponent<Button>().onClick.AddListener(() => { self.OnCloseBtn(0); });
                self.sureBtn = rc.Get<GameObject>("sureBtn");
                self.sureBtn.GetComponent<Button>().onClick.AddListener(() => { self.OnCloseBtn(1); });
                Dictionary<string,object> dic = param[0] as Dictionary<string,object>;
                string title = dic["title"] as string;
                string content = dic["content"] as string;
                string yesTxt = dic["yesTxt"] as string;
                string cancelTxt = dic["cancelTxt"] as string;
                self.callback = dic["callback"] as Action<object>;
                self.Init(title, content, yesTxt, cancelTxt);
            }
        }

        private static void Init(this UIAlertComponent self, string title, string content, string yesTxt, string cancelTxt)
        {
            self.titleTxt.GetComponent<UnityEngine.UI.Text>().text = title;
            self.cancelTxt.GetComponent<UnityEngine.UI.Text>().text = cancelTxt;
            self.sureTxt.GetComponent<UnityEngine.UI.Text>().text = yesTxt;
            self.contentTxt.GetComponent<UnityEngine.UI.Text>().text = content;
        }

        public static async void OnCloseBtn(this UIAlertComponent self,int index)
        {
            await SoundManager.Instance.PlaySound("clickbtnsound");
            self.callback?.Invoke(index);
            self.callback = null;
            self.OnCloseAsync();
        }

        public static async void OnCloseAsync(this UIAlertComponent self)
        {
            await UIHelper.Remove(self.ClientScene(),UIType.UIAlert);
        }
    }
}