using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class PanelEndings : BasePanel
{
    [SerializeField] CanvasGroup mCvsBg;
    [SerializeField] RectTransform mRctBg;

    [SerializeField] Button mBtnMask;
    [SerializeField] GameObject mGobComplete;
    [SerializeField] Transform mCtnEndings;
    [SerializeField] GameObject mTplEndingCell;

    private int mLevelID;
    private LevelData mLvData;
    private List<EndingCell> mEndingList = new List<EndingCell>();
    private List<EndingCell> mAvailableCells = new List<EndingCell>();

    private void Awake()
    {
        UIUtils.BindBtn(mBtnMask, OnClickMask);
    }

    public override void OnClose()
    {
        base.OnClose();

        AudioManager.Instance.PlaySound(AudioClipType.UIClose);
    }

    public void Init(int pLevelID)
    {
        mLevelID = pLevelID;
        mLvData = GameConfig.Instance.GetLevelData(pLevelID);

        mRctBg.sizeDelta = new Vector2(mRctBg.sizeDelta.x, 150 + mLvData.Endings.Count * 60);

        mGobComplete.SetActive(PlayerData.Instance.EndingCountOfLevel(mLevelID) == mLvData.Endings.Count);

        RefreshEndingList();

        mCvsBg.alpha = 0;
        mRctBg.anchoredPosition = new Vector2(0, -160);

        mCvsBg.DOFade(1, 0.3f);
        mRctBg.DOAnchorPosY(100, 0.3f);

        if (PlayerData.Instance.EndingAdTipCountOfLevel(mLevelID) < mLvData.Endings.Count)
        {
            ToukaSDKManager.Instance.LogEventByUmengAdShow(Const.AdsEvtValue.UnlockSound);
        }
    }

    private void RefreshEndingList()
    {
        ClearCells();

        for (int i = 0; i < mLvData.Endings.Count; i++)
        {
            EndingCell tCell = GetNewCell();
            mEndingList.Add(tCell);
            tCell.Init(mLevelID, i);
        }
    }

    private EndingCell GetNewCell()
    {
        EndingCell tCell = null;

        if (mAvailableCells.Count <= mEndingList.Count)
        {
            tCell = Instantiate(mTplEndingCell, mCtnEndings).GetComponent<EndingCell>();
            tCell.transform.localScale = Vector3.one;
            mAvailableCells.Add(tCell);
        }

        tCell = mAvailableCells[mEndingList.Count];
        tCell.gameObject.SetActive(true);

        return tCell;
    }

    private void ClearCells()
    {
        mEndingList.Clear();
        for (int i = 0; i < mAvailableCells.Count; i++)
        {
            mAvailableCells[i].gameObject.SetActive(false);
        }
    }

    private void OnClickMask()
    {
        mCvsBg.DOFade(0, 0.3f);
        mRctBg.DOAnchorPosY(-160, 0.3f).onComplete = Close;
    }
}