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

public class MonsterSpawner : MonoBehaviour {

    public Transform[] spawnPoints;

    public MonsterPack[] monsterPacks;

    public float spawnInterval;

    public float spawnIntervalRamp;

    public float maxValue;

    float delay;

    int nextSpawnPoint;

    float rampUpTime;

    // Use this for initialization
    void Start () {
        delay = spawnInterval;
        rampUpTime = 30 * Mathf.PI;
    }

    public float debugSin;
	
	// Update is called once per frame
	void Update () {
        delay -= Time.deltaTime;
        if (delay <= 0)
        {
            Monster[] monsters = GameObject.FindObjectsOfType<Monster>();
            float total = 0;
            for (int i = 0; i < monsters.Length; i++)
            {
                total += monsters[i].value;
            }

            if (total < maxValue)
            {
                SpawnMonster();
            }

            delay += spawnInterval - spawnIntervalRamp * (Mathf.Sin(rampUpTime / 20f) + 1f);
        }

        rampUpTime += Time.deltaTime;
    }

    void SpawnMonster()
    {
        float totalPriority = 0;
        for (int i = 0; i < monsterPacks.Length; i++)
        {
            totalPriority += monsterPacks[i].priority;
        }

        float chosen = Random.Range(0, totalPriority);
        MonsterPack chosenPack = null;
        totalPriority = 0;
        for (int i = 0; i < monsterPacks.Length; i++)
        {
            totalPriority += monsterPacks[i].priority;
            if (totalPriority >= chosen)
            {
                chosenPack = monsterPacks[i];
                break;
            }
        }
        if (chosenPack == null)
            chosenPack = monsterPacks[monsterPacks.Length - 1];

        Transform spawnPoint = spawnPoints[nextSpawnPoint];
        nextSpawnPoint = (nextSpawnPoint + 1) % spawnPoints.Length;

        for (int i = 0; i < chosenPack.monstersPosition.Length; i++)
        {
            GameObject.Instantiate(chosenPack.monstersPrefab[i], spawnPoint.position + spawnPoint.rotation * chosenPack.monstersPosition[i].position, spawnPoint.rotation * chosenPack.monstersPosition[i].rotation);
        }
    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        for (int i = 0; i < spawnPoints.Length; i++)
        {
            Gizmos.DrawSphere(spawnPoints[i].position, 0.5f);
            Gizmos.DrawRay(spawnPoints[i].position, spawnPoints[i].forward);
        }
    }
}
