namespace ChillConnect
{
    public class JoastUICtrl : BaseUICtrl
    {
        private JoastUI ui;
        private JoastModel model;

        private uint openUIMsg = UICtrlMsg.SCTipsUI_Open;
        private uint closeUIMsg = UICtrlMsg.SCTipsUI_Close;

        #region 生命周期

        protected override void OnInit()
        {
            model = moduleManager.GetModel(ModelConst.JoastModel) as JoastModel;
        }

        protected override void OnDispose()
        {
        }

        public override void OpenUI(object args = null)
        {
            if (ui == null)
            {
                ui = new JoastUI(this);
                ui.Open(args);
            }
        }

        public override void CloseUI(object args = null)
        {
            if (ui != null && !ui.isClose)
            {
                ui.Close();
            }

            ui = null;
        }

        #endregion

        #region 消息

        public override uint GetOpenUIMsg(string uiName)
        {
            return openUIMsg;
        }

        public override uint GetCloseUIMsg(string uiName)
        {
            return closeUIMsg;
        }

        protected override void AddListener()
        {
            uiCtrlDispatcher.AddListener(openUIMsg, AddTips);
            uiCtrlDispatcher.AddListener(closeUIMsg, CheckNext);
        }

        private void CheckNext(object obj)
        {
            JoastData joastData = obj as JoastData;
            joastData.Rest();
            CloseUI();
            ShowTips();
        }

        private void ShowTips()
        {
            if (ui != null) return;
            JoastData joastData = model.GetTips();
            if (joastData != default)
            {
                OpenUI(joastData);
            }
        }

        private void AddTips(object obj)
        {
            JoastData joastData = obj as JoastData;
            if (joastData == default) return;
            model.AddTips(joastData);
            ShowTips();
        }

        protected override void RemoveListener()
        {
            uiCtrlDispatcher.RemoveListener(openUIMsg, AddTips);
            uiCtrlDispatcher.RemoveListener(closeUIMsg, CheckNext);
        }

        #endregion
    }
}