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

public class DialogState : State {
    [SerializeField] private PixelFontMesh questionLabel = null; // Set from editor
    public const int maxSize = 4;
    [SerializeField] private PixelFontMesh[] answerLabel = new PixelFontMesh[maxSize]; // Set from editor
    [SerializeField] private Answer[] answers = new Answer[maxSize]; // Set from editor
    [SerializeField] private Color activeAnswerColor = Color.white; // Set from editor
    [SerializeField] private Color inactiveAnswerColor = Color.gray; // Set from editor
    [SerializeField] private DialogProcessor dialog = null;
    [SerializeField] private Container container = null;

    private int maxNodeSize = maxSize;
    private int currentSelectorId = 0;
    Dictionary<string, string> texts = null;


    internal void InitQuest(string questName, Container container, Dictionary<string, string> textVariables = null) {
        var dialogData = Dialog.LoadFromResources("Configs/" + questName);
        dialogData.PatchShowingCheck("u" + container["id"].ToString());
        this.container = container;
        texts = textVariables;
        dialog = new DialogProcessor(dialogData, container);
        SetDialogNode(dialog.CurrentNode);
        SetSelectorPosition(0);
    }

    private void SetDialogNode(Node currentNode) {
        if (currentNode == null) {
            questionLabel.Text = "Empty node: " + dialog.CurrentNodeId;
            foreach (var label in answerLabel) {
                answerLabel[1].Text = "";
            }
            return;
        }
        questionLabel.Text = ReplaceTagValues(currentNode.text, container);
        List<Answer> availableAnswers = currentNode.GetAvailableAnswers(container);
        maxNodeSize = availableAnswers.Count;
        for (int i = 0; i < maxSize; i++) {
            if (i < availableAnswers.Count) {
                answerLabel[i].Text = ReplaceTagValues(availableAnswers[i].text, container);
                answers[i] = availableAnswers[i];
            } else {
                answerLabel[i].Text = "";
                answers[i] = null;
            }
        }
        SetSelectorPosition(currentSelectorId);
    }

    private string ReplaceTagValues(string inputText, Container container) {
        const string replacePattern = "\\[(.*?)\\]";
        if (string.IsNullOrEmpty(inputText)) {
            return string.Empty;
        }
        MatchCollection matches = Regex.Matches(inputText, replacePattern);

        if (matches.Count > 0) {
            string result = inputText;
            foreach (Match match in matches) {
                string variableId = match.Groups[1].ToString();
                var symbolTag = string.Format("[{0}]", variableId);
                if (texts != null && texts.ContainsKey(variableId)) {
                    result = result.Replace(symbolTag, texts[variableId]);
                } else {
                    result = result.Replace(symbolTag, container[variableId].ToString());
                }
            }
            return result;
        }
        return inputText;
    }

    private void SelectCurrentAnswer() {
        dialog.SelectAnswer(answers[currentSelectorId]);
        if (dialog.IsDialogEnded()) {
            PlayerData.EndQuest();
        } else {
            SetDialogNode(dialog.CurrentNode);
        }
    }

    private void SetSelectorPosition(int id) {
        currentSelectorId = id;
        currentSelectorId = Mathf.Clamp(currentSelectorId, 0, maxNodeSize - 1);
        for (int i = 0; i < maxSize; i++) {
            var isActive = (i == currentSelectorId);
            answerLabel[i].SetColor(isActive ? activeAnswerColor : inactiveAnswerColor);
        }
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.W)) {
            SetSelectorPosition(currentSelectorId - 1);
        }
        if (Input.GetKeyDown(KeyCode.S)) {
            SetSelectorPosition(currentSelectorId + 1);
        }
        if (Input.GetKeyDown(KeyCode.UpArrow)) {
            SetSelectorPosition(currentSelectorId - 1);
        }
        if (Input.GetKeyDown(KeyCode.DownArrow)) {
            SetSelectorPosition(currentSelectorId + 1);
        }
        if (Input.GetKeyDown(KeyCode.D)) {
            SelectCurrentAnswer();
        }
        if (Input.GetKeyDown(KeyCode.RightArrow)) {
            SelectCurrentAnswer();
        }
        if (Input.GetKeyDown(KeyCode.Z)) {
            SelectCurrentAnswer();
        }
        if (Input.GetKeyDown(KeyCode.Space)) {
            SelectCurrentAnswer();
        }
        if (Input.GetKeyDown(KeyCode.F10)) {
            Show<PixelMapState>().ResetGame();
        }
        if (Input.GetKeyDown(KeyCode.Escape)) {
            Application.Quit();
        }
    }
}
