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

public class DialogueVoice : MonoBehaviour
{
    [Tooltip("How fast characters will display when speaking.")]
    [Range(0.8f, 1.0f)]
    public float talkSpeed;

    [Tooltip("Character will say a letter every 'n' characters, where the speech interval is 'n'.")]
    [Range(1, 5)]
    public int speechInterval;

    public Voices voice;

    private Dictionary<char, AudioClip> charToSoundMap;

    private void Start()
    {
        charToSoundMap = new Dictionary<char, AudioClip>();

        string path = GetVoicePath(voice);

        if (path != "")
        {
            MapVoices(Resources.LoadAll<AudioClip>(path));
        }
    }

    public AudioClip GetClipFromChar(char ch)
    {
        if (charToSoundMap.Count <= 0)
            return null;

        if (charToSoundMap.ContainsKey(ch))
        {
            return charToSoundMap[ch];
        }

        return charToSoundMap.ElementAt(Random.Range(0, charToSoundMap.Count)).Value;
    }

    private string GetVoicePath(Voices voice)
    {
        switch (voice)
        {
            case Voices.Voice_1:
                return "VoiceClips/male_voice1";
            case Voices.Voice_2:
                return "VoiceClips/female_voice1";
            default:
                return "";
        }
    }

    private void MapVoices(AudioClip[] voiceClips)
    {
        foreach (AudioClip clip in voiceClips)
        {
            if (clip.name.Length > 0)
            {
                if (clip.name == "period")
                {
                    charToSoundMap.Add('.', clip);
                }
                else
                {
                    // map first char of name to clip
                    charToSoundMap.Add(clip.name[0], clip);
                }
                
            }
        }
    }
}

public enum Voices
{
    None,
    Voice_1,
    Voice_2
}
