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

public class NPCSpawner : MonoBehaviour {
    public float lineGap;
    public float spawnPosition;
    public float spawnInterval;
    public int stadiumRadius;

    bool even = true;
    float spawnTime = 0f;

    float grumpChance = 5;
    float bonusChance = 1;

    float count = 0;

    public bool boss = false;

    bool end = false;

    public float bossInterval = 5f;
    public float bossTimer = 0f;

    private void Awake()
    {
        Observer.bossApproachesHandler += ToggleBoss;
        Observer.bossCleanupHandler += ToggleBoss;
        Observer.grumpTouchedHandler += ToggleEnd;
    }

    void ToggleEnd(NPC npc)
    {
        end = true;
    }

    void ToggleBoss()
    {
        bossTimer = 0f;
        boss = !boss;
    }

    private void FixedUpdate()
    {
        if (GlobalVariables.paused || end) return;
        spawnTime += Time.deltaTime;
        float camRatio = Camera.main.orthographicSize / GlobalVariables.minSize;
        if (spawnTime >= (spawnInterval / camRatio))
        {
            if (even) SpawnEvenLines();
            else SpawnOddLines();
            even = !even;
            spawnTime = 0f;

            //DO NOT DELETE -- THIS IS FOR GENERATING THE FIRST "SCREEN" OF NPC'S
            //Uncomment if you need to regenerate the first screen

           /* count += spawnInterval;
            if (count >= 80 * spawnInterval)
                Time.timeScale = 0;*/
        }
        if (!boss)
        {
            bossTimer += Time.deltaTime;
            if (bossTimer >= bossInterval)
            {
                Observer.OnBossApproaches();
            }
        }
    }

    void SpawnEvenLines()
    {
        for (int i = -stadiumRadius + 1; i < stadiumRadius; i += 2)
        {
            if (!boss && Random.Range(0, 100) < bonusChance) Pool.SpawnNewNPC(NPC.NPCState.BONUS, new Vector3(spawnPosition, i * lineGap, i)).transform.SetParent(this.transform);
            else if (!boss && Random.Range(0, 100) < grumpChance) Pool.SpawnNewNPC(NPC.NPCState.GRUMP, new Vector3(spawnPosition, i * lineGap, i)).transform.SetParent(this.transform);
            else Pool.SpawnNewNPC(NPC.NPCState.NEUTRAL, new Vector3(spawnPosition, i * lineGap, i)).transform.SetParent(this.transform);
        }
    }

    void SpawnOddLines()
    {
        for (int i = -stadiumRadius; i < stadiumRadius + 1; i += 2)
        {
            if (!boss && Random.Range(0, 100) < bonusChance) Pool.SpawnNewNPC(NPC.NPCState.BONUS, new Vector3(spawnPosition, i * lineGap, i)).transform.SetParent(this.transform);
            else if (!boss && Random.Range(0, 100) < grumpChance) Pool.SpawnNewNPC(NPC.NPCState.GRUMP, new Vector3(spawnPosition, i * lineGap, i)).transform.SetParent(this.transform);
            else Pool.SpawnNewNPC(NPC.NPCState.NEUTRAL, new Vector3(spawnPosition, i * lineGap, i)).transform.SetParent(this.transform);
        }
    }
}
