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

namespace ToadieTechnika.GGJ2018Game
{
    public class LevelCardsController : MonoBehaviour
    {
        [SerializeField]
        List<LevelCard> m_LevelCards = new List<LevelCard>();
        int m_lastOpenedLevel = -1;

        #region Properties
        public int GetLevelsCount
        {
            get { return m_LevelCards.Count; }
        }

        public bool SetLevelCardsVisible
        {
            set
            {
                foreach (LevelCard _LevelCard in m_LevelCards)
                    _LevelCard.gameObject.SetActive(value);
            }
        }
        #endregion

        #region Unity Functions
        void Start()
        {
            SetLevelCardsVisible = false;
        }
        #endregion

        #region Functions
        public void CatchLevelCards()
        {
            //Reset Level Cards
            m_LevelCards.Clear();

            for (int i = 0; i < transform.childCount - 1; i++)
            {
                m_LevelCards.Add(transform.GetChild(i).GetComponent<LevelCard>());
                m_LevelCards[i].gameObject.SetActive(false);
            }
        }

        public void InitiateLevel()
        {
            //Set last level invisible
            if (m_lastOpenedLevel != -1)
                m_LevelCards[m_lastOpenedLevel].gameObject.SetActive(false);

            //Open Level
            int _GetCurrentLevel = GameController.instance.PlayerData.CurrentLevel;
            LevelCard _CurrentLevelCard = m_LevelCards[_GetCurrentLevel];

            _CurrentLevelCard.gameObject.SetActive(true);
            m_lastOpenedLevel = _GetCurrentLevel;

            //Spawn stuff
            for (int i = 0; i < _CurrentLevelCard.PlayerPoints.Count; i++)
            {
                GameObject _NewPhoneUnit = ObjectPooler.instance.CreateObject(PooledObjectsEnum.PhoneUnit, _CurrentLevelCard.PlayerPoints[i].position, Quaternion.identity) as GameObject;


                PhoneUnitScript _GetPhoneUnit = _NewPhoneUnit.GetComponent<PhoneUnitScript>();
                _GetPhoneUnit.InitiatePhoneUnit(i);

                GameplayController.instance.CurrentPhoneUnits.Add(_GetPhoneUnit);
            }

            //Set Stats
            GameplayController.instance.CollectForEndLeft = _CurrentLevelCard.GetItemsForEndLength;
            GameplayController.instance.CurrentSatellites = _CurrentLevelCard.Satellites;
            GameplayController.instance.CurrentBluetoothObjects = _CurrentLevelCard.BluetoothObjects;

            //Finalize!
            _CurrentLevelCard.NormalizeLevel();
        }
        #endregion
    }
}