using BingoBrain.Core;
using BingoBrain.HotFix;

namespace BingoBrain
{
    public class DialogSystem : BaseSystem
    {
        public DialogSystem(bool isAutoInit = true)
        {
            if (isAutoInit)
            {
                Init();
            }
        }

        Gsss startGameSequence = new Gsss();
        Gsss backMainSequence = new Gsss();

        public sealed override void Init()
        {
            base.Init();

            AddListener();
        }

        private void AddListener()
        {
            CtrlDispatcher.Instance.AddOnceListener(CtrlMsg.Game_Start, StartGame);
            GameDispatcher.Instance.AddFinallyListener(BingoInfo.EndBingoGame, OnEndBingoGame);
        }

        private void StartGame(object obj)
        {
            startGameSequence.Clear();

            if (GameHelper.IsOpenGuide())
            {
                AddOpenReward(startGameSequence);
            }

            if (startGameSequence.Count == 0)
            {
                // End();
            }
            else
            {
                startGameSequence.Run();
            }
        }

        private void OnEndBingoGame(object obj)
        {
            var isBackMain = (bool)obj;
            if (isBackMain)
            {
                BackMain();
            }
        }

        private void BackMain()
        {
            backMainSequence.Clear();

            AddOpenReward(backMainSequence);

            if (backMainSequence.Count == 0)
            {
            }
            else
            {
                backMainSequence.Run();
            }
        }

        private bool isFinishNaive;

        private void AddOpenReward(Gsss gsss)
        {
            if (!GameHelper.IsGiftSwitch())
            {
                return;
            }

            if (PreferencesMgr.Instance.IsShowOpenReward)
            {
                gsss.Add(true, (procedure) =>
                {
                    UICtrlDispatcher.Instance.Dispatch(SkinInfo.OpenRewardUI_Open);
                    UICtrlDispatcher.Instance.AddOnceListener(SkinInfo.OpenRewardUI_Close,
                        e => { procedure.InvokeComplete(); });
                });
            }
        }
    }
}