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

namespace ToadieTechnika.GGJ2018Game
{
    public enum SFX
    { 
        GetMessage,
        MessageSent,
        LevelFinished,
        SwapUnit,
        TransmissionUnlock,
        TransmissionLock,
        TransmissionAttract,
        PlayerExplode,
        BluetoothPanel,
        SatelliteConnect,
        Interference,
        UnitJump,
        GameButton,

        Length
    }

    public enum PlayerDataState
    {
        Save,
        Load,
    }

    public class GameController : GenericSingleton<GameController>
    {
        PlayerData m_PlayerData = new PlayerData();

        [SerializeField]
        AudioSource m_SoundSource;
        List<AudioClip> m_AudioClips = new List<AudioClip>();

        #region Properties
        public PlayerData PlayerData
        {
            get { return m_PlayerData; }
            set { m_PlayerData = value; }
        }
        #endregion

        protected override void Awake()
        {
            singletonNonOneSceneEvent = delegate
            {
                //Force persistent
                PlayerDataManipulation(PlayerDataState.Load);

                //Load Sounds
                m_AudioClips.Clear();
                for (int i = 0; i < (int)SFX.Length; i++)
                {
                    AudioClip _GetAudioClip = Resources.Load<AudioClip>("Sounds/" + ((SFX)i).ToString());
                    m_AudioClips.Add(_GetAudioClip);
                }
            };

            base.Awake();
        }

        public void PlayerDataManipulation(PlayerDataState _WhichState)
        {
            string _PlayerDataPref = "PlayerData";
            bool _PlayerDataExists = PlayerPrefs.HasKey(_PlayerDataPref);

            switch (_WhichState)
            {
                case PlayerDataState.Save:
                    PlayerPrefs.SetString(_PlayerDataPref, JsonMapper.ToJson(m_PlayerData).ToString());
                    break;
                case PlayerDataState.Load:
                    if (_PlayerDataExists)
                        m_PlayerData = JsonMapper.ToObject<PlayerData>(PlayerPrefs.GetString(_PlayerDataPref));
                    break;
            }
        }

        public void PlaySound(SFX _WhichSFX, float _SetVolume = 1f)
        {
            m_SoundSource.PlayOneShot(m_AudioClips[(int)_WhichSFX], _SetVolume);
        }

        public void PlayRandomSound(SFX[] _SFXs, float _SetVolume = 1f)
        {
            int _SoundIndex = (int)_SFXs[Random.Range(0, _SFXs.Length)];
            m_SoundSource.PlayOneShot(m_AudioClips[_SoundIndex], _SetVolume);
        }
    }

    public class PlayerData
    {
        int m_CurrentLevel;

        #region Properties
        public int CurrentLevel
        {
            get { return m_CurrentLevel; }
            set { m_CurrentLevel = value; }
        }
        #endregion
    }
}