using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    [Header("Game Generation Phase")]
    public int numberOfTurns = 50;
    public int NumberOfPeople = 10;

    [Header("Scene refrences")]
    public Booth entrance;
    public GameObject[] boothNodes;

    [Header("Prefabs")]
    public GameObject playerPrefab;

    [Header("People Assets")]
    public TextAsset names;
    public TextAsset bios;
    private string[] storedNames;
    private string[] storedBios;
	private Sprite[] bioImages;
    private GameObject[] sprites;

	[Header("Music")]
	public AudioSource standingMusic;
	public AudioSource walkingMusic;

    public List<Npc> npcs = new List<Npc>();
    private List<Booth> booths = new List<Booth>();
    private int currentTimeStep = 0;


    [Header("Parent")]
    public GameObject god;
    public List<Npc> notSick;
    private ImortalStorage im;

    void Start()
    {
        
    }

    private void Awake()
    {
        im = GameObject.FindGameObjectWithTag("Imortal").GetComponent<ImortalStorage>();
        storedNames = Regex.Split(names.text, "\r\n");
        storedBios = Regex.Split(bios.text, "\r\n");
        bioImages = Resources.LoadAll<Sprite>("BioImages");
        sprites = Resources.LoadAll<GameObject>("NPCSprites");

        SetupMusic();

        //Start the game
        GenerateGame();
    }

    void SetupMusic()
	{
		if (standingMusic != null)
		{
			standingMusic.Play();
		}

		if (walkingMusic != null)
		{
			walkingMusic.Play();
		}

		PlayMusic(false);
	}

    void Update()
    {
       // if (Input.GetKeyDown(KeyCode.L)) GoToEnd();
    }

    void GenerateGame()
    {
        //Create our player
        createPlayer();
        //Create our normal people
        for (int i = 0; i < NumberOfPeople-1; i++)
		{
			CreateNpc(false, i);
		}

		//Create our patient zero
		CreateNpc(true, 9999);

		//Find our booths and child them to god
		booths.AddRange(FindObjectsOfType<Booth>());
        
        //make god the parent of all our booths
        foreach(Booth booth in booths)
        {
            booth.transform.parent = god.transform;
            booth.GetComponent<Booth>().InitBooth(numberOfTurns);
        }
    }

	private void CreateNpc(bool infected, int id)
	{
		//Create the person from the prefab
		GameObject person = Instantiate(sprites[Random.Range(0, sprites.Length)], entrance.transform.position + new Vector3(0, 1.5f, 0), Quaternion.identity);
		person.transform.parent = god.transform;
        person.name = "Person" + id.ToString();
        
        //set up the NPC script
        Npc npc = person.GetComponent<Npc>();
        npcs.Add(npc);
		var name = storedNames[Random.Range(0, storedNames.Length - 1)];
		var bio = storedBios[Random.Range(0, storedBios.Length - 1)];
		var image = bioImages[Random.Range(0, bioImages.Length - 1)];

		npc.InitNpc(name, bio, infected, numberOfTurns, entrance, image);
	}

	void createPlayer()
    {
        GameObject player = Instantiate(Resources.Load<GameObject>("PlayerSprite"), entrance.transform.position + new Vector3(0, 1.5f, 0), Quaternion.identity);
        player.name = "PlayerCharacter";
        player.transform.parent = god.transform;
        FindObjectOfType<PlayerController>().InitPlayerCharacter(player);
    }

    public bool stepForward()
    {
        if(currentTimeStep < numberOfTurns)
        {
            currentTimeStep++;
            Booth.currTime++;
            Npc.currTime++;
            Player.currTime++;
            god.BroadcastMessage("StepForward");
            god.BroadcastMessage("BoothStepForward");
            return true;
        }
        else return false;
    }
    public bool stepBack()
    {
        if (currentTimeStep > 0)
        {
            currentTimeStep--;
            Booth.currTime--;
            Npc.currTime--;
            Player.currTime--;
            god.BroadcastMessage("StepBack");
            god.BroadcastMessage("BoothStepBack");
            return true;
        }
        else return false;
    }
    public int GetCurrentTimeStep()
    {
        return currentTimeStep;
    }

	public void PlayMusic(bool isMoving)
	{
		if (standingMusic != null && walkingMusic != null)
		{
			standingMusic.volume = isMoving ? 0f : 0.25f;
			walkingMusic.volume = isMoving ? 0.25f : 0f;
		}
	}

    public void GoToEnd()
    {

        for (int j = currentTimeStep; j < numberOfTurns; j++)
        {
            stepForward();
        }
        int length = npcs.Count;
        int safe = npcs.FindAll(s => s.Infected[numberOfTurns - 1] == false).Count;
        
        im.UpdateScore(safe);
        SceneManager.LoadScene(2);
    }
}

