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

public class DogPhrasingHandler : MonoBehaviour
{
	[SerializeField] private string deathRattle = "Death_1";

	private Dictionary<string, string> phrasing = new Dictionary<string, string>();

	public void LearnPhrase(string key, string value)
	{
		phrasing[key] = value;
	}

	public string DeathRattle
	{
		get
		{
			return deathRattle;
		}
	}

	public bool HasLearnedPhrase(string key)
	{
		return phrasing.ContainsKey(key);
	}

	public string GetPhrase(string key)
	{
		return ProcessPhrase(phrasing[key]);
	}

	private string ProcessPhrase(string phrase)
	{
		if (Regex.IsMatch(phrase, PhraseConfigurationManager.SubstitutionPattern))
		{
			phrase = ProcessSubstitutions(phrase);
		}

		if (GameManager.HardMode)
		{
			phrase = ProcessHardMode(phrase);
		}

		return phrase;
	}

	private string ProcessSubstitutions(string phrase, int depth = 0)
	{
		if (depth > PhraseConfigurationManager.MaxProcessingDepth)
		{
			DogManager.Kill();
		}
		MatchCollection matchCollection = Regex.Matches(phrase, PhraseConfigurationManager.SubstitutionPattern);

		foreach (Match match in matchCollection)
		{
			if (match.Success)
			{
				GroupCollection groupCollection = match.Groups;

				foreach (Group group in groupCollection)
				{
					if (group.Success && group.Value != match.Value)
					{
						try
						{
							if (phrasing.ContainsKey(group.Value))
							{
								string dogPhrase = ProcessSubstitutions(phrasing[group.Value], depth + 1);
								phrase = Regex.Replace(phrase, match.Value, dogPhrase);
							}
						}
						catch (System.Exception e)
						{
							GameManager.Log(e);
						}
					}
				}
			}
		}

		return phrase;
	}

	private string ProcessHardMode(string phrase)
	{
		int count = phrase.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries).Length;
		phrase = PhraseConfigurationManager.HardWord;

		for (int i = 0; i < count - 1; i++)
		{
			phrase += " " + PhraseConfigurationManager.HardWord;
		}

		return phrase;
	}
}