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

public class GameModel : MonoBehaviour {

    [System.Serializable]
    class Level
    {
        public GameObject map;
        public List<GameObject> enemies;
    }

    public Tank player;
    public IGDCBase IGDCBase;
    public List<Tank> enemyList;
    public int _lives;
    public float spawnRate;
    public bool isWin = false;
    private float _lastSpawn;
    static public int level = 0;

    [SerializeField] private List<Level> _levels;
    [SerializeField] private List<GameObject> _spawns;

    public int lives
    {
        get { return _lives; }
        set {
                _lives = value;
                if (_lives == -1)
                {
                    Time.timeScale = 0.0f;
                    Screen.lockCursor = false;
                }
        }
    }

    void Start()
    {
        Random.seed = System.DateTime.Now.Second;
        IGDCBase = FindObjectOfType(typeof(IGDCBase)) as IGDCBase;
        Time.timeScale = 1.0f;
        InitLevel();
    }

    void InitLevel()
    {
        _lastSpawn = -spawnRate;
    }


    public void RegisterTank(Tank tank)
    {
        switch (tank.fraction)
        {
            case 0: enemyList.Add(tank); break;
            case 1: player = tank; break;
        }
    }

    public void UnRegister(Tank tank)
    {
        switch (tank.fraction)
        {
            case 0: enemyList.Remove(tank); break;
            case 1: player = null; break;
        }
    }

    void Update()
    {
        if (Time.time - _lastSpawn > spawnRate)
        {
            if (_levels[level].enemies.Count > 0){
                var enemy = _levels[level].enemies[0];
                var spawn = _spawns[Random.Range(0, _spawns.Count - 1)];
                Instantiate(enemy, spawn.transform.position, Quaternion.Euler(0f, Random.value * 360f, 0f));

                _levels[level].enemies.RemoveAt(0);
            }

            _lastSpawn = Time.time;
        }

        if ((_levels[level].enemies.Count == 0) && (enemyList.Count == 0))
        {

            if (level == _levels.Count - 1)
            {
                isWin = true;
                Time.timeScale = 0.0f;
                Screen.lockCursor = false;
            }
            else
            {
                level += 1;
                Application.LoadLevel("Game");
            }

        }
	}
}
