using UnityEngine;
using System.Collections;

public class TypingController : MonoBehaviour {

    public TextMesh meshPrefab;

    public AudioClip typeSound;
    public float typeVolume = 1f;

    public AudioClip correctSound;
    public float correctVolume = 1f;

    private static Color rightColor = new Color(0.2f, 0.6f, 0.4f, 1.0f);
    private static Color wrongColor = new Color(0.6f, 0.2f, 0.0f, 1.0f);

    private static TextMesh textMesh;
    private static bool locked = false;

    private GameObject soundManager;

	// Use this for initialization
	void Start() {
        textMesh = transform.GetChild(0).GetComponent<TextMesh>();
        SetLocked(true);

        soundManager = GameObject.FindGameObjectWithTag("SoundManager");
    }
	
	// Update is called once per frame
	void Update() {
        if (locked) return;

        // Check answer
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Return)) {
            bool correct = CheckAnswer();

            ReplaceMesh(correct);
            if (correct) {
                SoundUtils.playSound(soundManager, correctSound, correctVolume);
                ChapterManager.GoToNextSentence();
            }
        }

        // Type letter
        if (Input.anyKeyDown && Input.inputString.Length > 0) {
            TypeLetter(Input.inputString[0]);
        }
    }

    public static void SetLocked(bool isLocked) {
        if (isLocked) ReplaceMesh(false);
        locked = isLocked;
    }

    void TypeLetter(char letter) {
        if (letter >= 'a' || letter <= 'z') {
            textMesh.text += letter;
            SoundUtils.playSound(soundManager, typeSound, typeVolume);
        }
    }

    bool CheckAnswer() {
        print("Checking answer...");
        string temp = textMesh.text.Trim();

        if (temp.Length >= ChapterManager.Word.Length) {
            int startIndex = temp.LastIndexOf(' ') + 1;

            string answer = temp.Substring(startIndex);

            if (answer == ChapterManager.Word) {
                print("Correct!");
                return true;
            }
        }

        print("Incorrect.");
        return false;
    }

    static void ReplaceMesh(bool correct) {
        TextMesh oldMesh = textMesh;

        // Replace the old mesh
        Vector3 position = textMesh.transform.position;
        Quaternion rotation = textMesh.transform.rotation;

        GameObject meshPrefab = Resources.Load("prefabs/text meshes/Typing") as GameObject;
        GameObject mesh = Object.Instantiate(meshPrefab, position, rotation) as GameObject;
        mesh.transform.parent = oldMesh.transform.parent;
        textMesh = mesh.GetComponent<TextMesh>();

        // Destroy the old mesh
        TextController controller = oldMesh.GetComponent<TextController>();
        controller.fadeCol = (correct) ? rightColor : wrongColor;
        controller.FadeOut();
    }
}
