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

public class DogManager : SingletonBase<DogManager>
{
	public string deathRattleKeyBase = "Death_";
	public string dogUILocation = "Prefabs/UI/UI";

	public delegate void Speaking(string text);
	public static event Speaking OnSpeak;

	public delegate void Dead();
	public static event Dead OnDeath;

	public static void SpawnDog(Transform parentTransform)
	{
		if (dogManager.dog != null)
		{
			Kill();
		}

		if (dogManager.dogUIRoot)
		{
			Destroy(dogManager.dogUIRoot.gameObject);
		}

		dogManager.dogUIRoot = Instantiate(Resources.Load<GameObject>(dogManager.dogUILocation), parentTransform)?.transform;
		dogManager.dog = Instantiate(Resources.Load<GameObject>(dogManager.dogPrefabLocation), dogManager.dogUIRoot);
		dogManager.phrasing = dogManager.dog.GetComponent<DogPhrasingHandler>();
		dogManager.statistics = dogManager.dog.GetComponent<DogStatisticsHandler>();

		PhraseConfigurationManager.TeachPhrasing(dogManager.phrasing);
		StatisticsConfigurationManager.InitializeStatistics(dogManager.statistics);
	}

	public static void Speak(string key)
	{
		if (dogManager.dog != null)
		{
			string dialogue = dogManager.phrasing.GetPhrase(key);
			if (dialogue != null)
			{
				OnSpeak(dialogue);
			}
		}
	}

	public static void Kill()
	{
		if (dogManager.dog == null)
		{
			throw new System.Exception("Dog has not been initialized");
		}

		if (dogManager.phrasing == null)
		{
			throw new System.Exception("DogPhrasing has not been initialized");
		}

		int index = Random.Range(1, 6);
		string deathRattle = dogManager.deathRattleKeyBase + index;
		Speak(deathRattle);
		Destroy(dogManager.dog);
		OnDeath();
	}
	
	private static DogManager dogManager;
	private GameObject dog;
	private DogPhrasingHandler phrasing;
	private DogStatisticsHandler statistics;
	private Transform dogUIRoot = null;

	[SerializeField] private string dogPrefabLocation = "Prefabs/Entities/Dog";

	protected override void Awake()
	{
		base.Awake();
		dogManager = instance as DogManager;
	}

	private void OnEnable()
	{
		DogStatisticsHandler.OnStatisticChanged += WillToLive;
		Action.OnPerformed += ParseAction;
	}

	private void OnDisable()
	{
		DogStatisticsHandler.OnStatisticChanged -= WillToLive;
		Action.OnPerformed -= ParseAction;
	}

	private void WillToLive(Statistic statistic)
	{
		if (statistic.value <= statistic.min)
		{
			Kill();
		}
	}

	private void ParseAction(Action action)
	{
		if (action is SpawnAction)
		{
			SpawnDog(GameManager.UIRoot);
		}

		if (action.responses.Count > 0)
		{
			RespondToAction(action);
		}
	}

	private void RespondToAction(Action action)
	{
		int responseIndex = Random.Range(0, action.responses.Count);
		string responseKey = action.responses[responseIndex];

		Speak(responseKey);
	}
}
