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

public enum GameState {
    Playing,
    AllApplesCollected,
    PlayerCrashed
}

public class GameStateManager : MonoBehaviour {

    #region Unity Singleton Pattern
    private static GameStateManager instance = null;
    public static GameStateManager Instance {
        get { return instance; }
    }

    void Awake() {
        if (instance != null && instance != this) {
            Destroy(this.gameObject);
            return;
        } else {
            instance = this;
        }

        // Der GameStateManager gilt nur pro Szene => löschen!
        //DontDestroyOnLoad(this.gameObject);
    }
    #endregion Unity Singleton Pattern

    public UnityEvent onAppleCollected = new UnityEvent();
    public UnityEvent onGameStateChanged = new UnityEvent();

    private GameState currentGameState = GameState.Playing;
    public GameState CurrentGameState {
        get { return currentGameState; }
    }
    private List<Apple> allApplesInScene = new List<Apple>();

    public int AllApplesCount {
        get { return allApplesInScene.Count; }
    }

    public int CollectedApplesCount {
        get {
            int result = 0;
            foreach (Apple apple in allApplesInScene) {
                if (!apple.gameObject.activeSelf) {
                    result++;
                }
            }
            return result;
        }
    }

    public void Start() {
        FindApplesInScene();
        StartPlaying();
    }

    private void FindApplesInScene() {
        Apple[] apples = FindObjectsOfType<Apple>();
        allApplesInScene.AddRange(apples);
    }

    public void StartPlaying() {
        ChangeGameState(GameState.Playing);
    }

    public void PlayerCrashed() {
        ChangeGameState(GameState.PlayerCrashed);
    }

    public void AppleCollected() {
        onAppleCollected.Invoke();
        if (AllApplesCount == CollectedApplesCount) {
            ChangeGameState(GameState.AllApplesCollected);
        }
    }

    private void ChangeGameState(GameState newState) {
        currentGameState = newState;
        onGameStateChanged.Invoke();
    }

}
