using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LevelPage : PageView
{
    public Action<int> DelClickLevel;

    [SerializeField] GameObject mGobLeftArrow;
    [SerializeField] GameObject mGobRightArrow;

    private int mCurrentIndex = -1;

    protected override void AwakeInit()
    {
        OnScrollPage = PlayScrollPage;
        OnReachEdge = PlayReachEdge;

        OnPageChanged = PageChanged;
    }

    protected override void BeforeLoad()
    {
        mCurrentIndex = PlayerData.Instance.CurrentLevel - 1;
    }

    public LevelCell GetCell(int pIndex)
    {
        return mCellList[pIndex].GetComponent<LevelCell>();
    }

    public override int Count
    {
        get
        {
            int tTotalCount = GameConfig.Instance.LevelSort.Count + 1;//add coming soon
            int tUnlockedCount = PlayerData.Instance.UnlockedLevel;
            int tEnoughCount = ((tUnlockedCount - 1) / CountPerPage + 1) * CountPerPage;

            return Mathf.Min(tTotalCount, tEnoughCount);
        }
    }

    protected override void ConfigCell(GameObject pCellGob, int pIndex)
    {
        LevelCell tCell = pCellGob.GetComponent<LevelCell>();

        if (pIndex < PlayerData.Instance.UnlockedLevel)
        {
            tCell.Init(pIndex);
            tCell.ShowCurrent(pIndex == mCurrentIndex);
            tCell.DelClick = OnClickLevel;
        }
        else
        {
            if (pIndex < GameConfig.Instance.LevelSort.Count)
            {
                tCell.SetEmpty();
            }
            else
            {
                tCell.SetComingSoon();
            }
        }
    }

    private void OnClickLevel(int pLevelIndex)
    {
        if (mCurrentIndex >= 0)
        {
            mCellList[mCurrentIndex].GetComponent<LevelCell>().ShowCurrent(false);
        }

        mCurrentIndex = pLevelIndex;
        mCellList[mCurrentIndex].GetComponent<LevelCell>().ShowCurrent(true);

        DelClickLevel?.Invoke(pLevelIndex);
    }

    private void PageChanged(int pPageIndex)
    {
        mGobLeftArrow.SetActive(pPageIndex > 0);
        mGobRightArrow.SetActive(pPageIndex < PageCount - 1);
    }

    private void PlayScrollPage()
    {
        AudioManager.Instance.PlaySound(AudioClipType.TurnPage, 0.7f);
    }

    private void PlayReachEdge()
    {
        AudioManager.Instance.PlaySound(AudioClipType.ReachEdge, 0.7f);
    }
}