using System;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class MissionManager : MonoBehaviour
{
    public static readonly string MissionDataTag = "MissionData";
    private static readonly string TimeFormat = "更新まで：{0}時間{1}分{2}秒";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Button closeButton;
    [SerializeField] private MissionListView listView;
    [SerializeField] private Text timeLimitText;

    private void Start()
    {
        closeButton.OnClickAsObservable().Subscribe(_ =>
        {
            LocalCacheManager.Remove(MissionDataTag);
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.Mission);
            });
        }).AddTo(this);

        listView.SelectedTab.Subscribe(category =>
        {
            timeLimitText.gameObject.SetActive(category == MissionCategory.Daily);
        }).AddTo(this);

        // ミッション読み込み
        var missionList = SpreadsheetDataManager.Instance.GetBaseDataList<MissionData>(Const.MissionDataSheet);
        
        // ミッション表示
        foreach (var missionData in missionList)
        {
            var missionView = listView.AddItemView(missionData);
            var progressValue = GetProgressValue(missionData);
            missionView.SetData(missionData, progressValue);
            missionView.SetButtonActive(missionData.count <= progressValue);
            if (GameDataManager.GameData.AchievedMission.Contains(missionData.id)) // 達成済み
            {
                missionView.SetRewarded();
            }
            
            // リワード獲得
            missionView.RewardButton.ThrottleFirst(TimeSpan.FromSeconds(1f)).Subscribe(_ =>
            {
                LocalCacheManager.Save(MissionDataTag, (missionData, new Action(() =>
                {
                    GetReward(missionData);
                    missionView.SetRewarded();
                    // 達成ID保存
                    GameDataManager.GameData.AchievedMission.Add(missionData.id);
                })));
                TransitionManager.Instance.LoadSceneAdditive(GameScenes.MissionAchievement);
            }).AddTo(missionView);
        }
        listView.SetTab(MissionCategory.Daily);
    }

    private int GetProgressValue(MissionData missionData)
    {
        var gameData = GameDataManager.GameData;
        switch (missionData.Condition)
        {
            case MissionCondition.CornCount:
                return gameData.TotalAddCornSeed;
            case MissionCondition.CustomerCount: // タップor来客した数
                return gameData.TotalCustomerCount;
            case MissionCondition.SalesCount: // 売った数
                return gameData.TotalSales;
            case MissionCondition.RareSalesCount: // レアを売った数
                return gameData.RareTotalSales;
            case MissionCondition.RecipeCount: // レシピの数
                return gameData.MyRecipes.Length;
            case MissionCondition.CoinConsumeCount: // コイン消費数
                return gameData.TotalSubCoin;
            case MissionCondition.SaltSalesCount:
                return gameData.GetTotalSalesByFlavor(2);
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    private void GetReward(MissionData missionData)
    {
        if (missionData.RewardType == MissionRewardType.Coin)
        {
            CoinManager.Instance.AddCoinWithEffect(missionData.reward, () => {});
            GameDataManager.GameData.Coin = CoinManager.Instance.OwnCoin;
        }
    }
}