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

public class AnswerLineInfoScript : MonoBehaviour {

    [SerializeField] readonly Button nextPlayerButton;
    [SerializeField] readonly Button prevPlayerButton;
    [SerializeField] readonly Text lockedQuestionsText;
    [SerializeField] readonly Text unlockedQuestionsText;
    [SerializeField] readonly GameObject scrollView;
    [SerializeField] readonly GameObject answerLine;
    [SerializeField] readonly GameObject newQuestion;

    [SerializeField] readonly GameObject gameManager;
    private List<KeyValuePair<string, int>> players;
    private string currentPlayerShown;
    private String signedInName;
    private GameManagerScript gameManagerScript;

    private List<AnswerLineQuestionCard> signedInPlayerQuestions = new List<AnswerLineQuestionCard>();
    private void Start() {
        nextPlayerButton.onClick.AddListener(ShowNextPlayerAnswerLine);
        prevPlayerButton.onClick.AddListener(ShowPrevPlayerAnswerLine);
        signedInName = Database.Instance.GetSignedInUser().Value;
        lockedQuestionsText.resizeTextMaxSize = unlockedQuestionsText.resizeTextMaxSize;
        gameManagerScript = gameManager.GetComponent<GameManagerScript>();
    }

    private void Update() {
        UpdateLockedQuestionsText();
        UpdateUnlockedQuestionsText();
        UpdateButtonsText();
        SetQuestionClickable();
        if (signedInName.Equals(currentPlayerShown, StringComparison.InvariantCultureIgnoreCase) &&
            signedInPlayerQuestions != answerLine.GetComponentsInChildren<AnswerLineQuestionCard>().ToList()) {
            signedInPlayerQuestions = answerLine.GetComponentsInChildren<AnswerLineQuestionCard>().ToList();
        }
    }

    private void SetQuestionClickable() {
        List<KeyValuePair<string, int>> players = gameManagerScript.GetPlayers();
        if (gameManagerScript.GameStatus == null || !gameManagerScript.GameStatus.Equals("FINISHED")) {
            if (gameManagerScript.GameMode.Equals(Constants.ONLINE)) {
                if (players.Count > 1 && currentPlayerShown != null) {
                    if (GameManagerScript.GetCurrentPlayer().Equals(currentPlayerShown, StringComparison.InvariantCultureIgnoreCase)) {
                        newQuestion.GetComponent<NewQuestionCardController>().BackClickable = true;
                    } else {
                        newQuestion.GetComponent<NewQuestionCardController>().BackClickable = false;
                    }
                }
            } else {
                newQuestion.GetComponent<NewQuestionCardController>().BackClickable = true;
            }
        } else {
            newQuestion.GetComponent<NewQuestionCardController>().BackClickable = false;
        }
    }

    public void UpdateButtonsText() {
        if (players == null) {
            players = gameManagerScript.GetPlayers();
        }

        if (players.Count <= 1) {
            nextPlayerButton.gameObject.SetActive(false);
            prevPlayerButton.gameObject.SetActive(false);
        } else {
            nextPlayerButton.gameObject.SetActive(true);
            prevPlayerButton.gameObject.SetActive(true);

            if (gameManagerScript.GameMode.Equals(Constants.ONLINE) && currentPlayerShown == null) { // fungerar enbart vid online
                currentPlayerShown = signedInName;
            } else if (gameManagerScript.GameMode.Equals(Constants.LOCAL) && currentPlayerShown == null) {
                currentPlayerShown = Database.Instance.GetCurrentPlayer(gameManagerScript.GameId, gameManagerScript.GameMode);
            }

            string playerBaseText = LocalizationManager.Instance.GetText("ANSWERLINE_OTHER_PLAYER");
            for (int i = 0; i < players.Count; i++) {
                if (players[i].Key.Equals(currentPlayerShown, StringComparison.InvariantCultureIgnoreCase)) {
                    if (i + 1 < players.Count) {
                        if (players[i + 1].Key.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
                            nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = LocalizationManager.Instance.GetText("YOUR");
                        } else {
                            nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = players[i + 1].Key + "s";
                        }
                        nextPlayerButton.GetComponentInChildren<Text>().text = String.Format(playerBaseText, nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName);
                        if (i - 1 >= 0) {
                            if (players[i - 1].Key.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
                                prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = LocalizationManager.Instance.GetText("YOUR");
                            } else {
                                prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = players[i - 1].Key + "s";
                            }
                        } else {
                            if (players[players.Count - 1].Key.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
                                prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = LocalizationManager.Instance.GetText("YOUR");
                            } else {
                                prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = players[players.Count - 1].Key + "s";
                            }
                        }
                        prevPlayerButton.GetComponentInChildren<Text>().text = String.Format(playerBaseText, prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName);
                        break;
                    } else {
                        if (players[0].Key.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
                            nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = LocalizationManager.Instance.GetText("YOUR");
                        } else {
                            nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = players[0].Key + "s";
                        }
                        nextPlayerButton.GetComponentInChildren<Text>().text = String.Format(playerBaseText, nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName);

                        if (players[i - 1].Key.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
                            prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = LocalizationManager.Instance.GetText("YOUR");
                        } else {
                            prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName = players[i - 1].Key + "s";
                        }
                        prevPlayerButton.GetComponentInChildren<Text>().text = String.Format(playerBaseText, prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName);
                        break;
                    }
                }
            }
        }
    }

    private void UpdateUnlockedQuestionsText() {
        int unlockedQuestionCount = scrollView.GetComponent<ScrollViewScript>().GetUnlockedQuestionCount();
        if (unlockedQuestionCount <= 0) {
            unlockedQuestionsText.gameObject.SetActive(false);
        } else {
            unlockedQuestionsText.gameObject.SetActive(true);
            unlockedQuestionsText.text = String.Format(
                LocalizationManager.Instance.GetText(
                    unlockedQuestionsText.GetComponent<TextLocalization>().key),
                unlockedQuestionCount);
        }
    }

    private void UpdateLockedQuestionsText() {
        ScrollViewScript scrollViewScript = scrollView.GetComponent<ScrollViewScript>();
        int lockedQuestionsCount = scrollViewScript.GetQuestionIdsInAnswerLine().Count - scrollViewScript.GetUnlockedQuestionCount();
        String playerText;
        if (currentPlayerShown == null || currentPlayerShown.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
            playerText = LocalizationManager.Instance.GetText("YOU");
        } else {
            playerText = currentPlayerShown;
        }

        if (lockedQuestionsText != null) {
            lockedQuestionsText.text = String.Format(
                LocalizationManager.Instance.GetText(
                    lockedQuestionsText.GetComponent<TextLocalization>().key),
                    playerText,
                    lockedQuestionsCount);
        }
    }

    private void ShowNextPlayerAnswerLine() {
        if (nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName.Equals(LocalizationManager.Instance.GetText("YOUR"))) {
            currentPlayerShown = signedInName;
        } else {
            currentPlayerShown = nextPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName;
            currentPlayerShown = currentPlayerShown.Substring(0, currentPlayerShown.Length - 1);
        }

        if (currentPlayerShown.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
            List<NewQuestionData> questions = new List<NewQuestionData>();
            foreach (AnswerLineQuestionCard aq in signedInPlayerQuestions) {
                questions.Add(new NewQuestionData(aq.GetAnswerText(), aq.GetQuestionText(), aq.CategoryText, aq.CategoryId, aq.QuestionId, aq.CategoryColor, aq.QuestionSafe));
            }
            setQuestionFrosting(questions);
        } else {
            List<NewQuestionData> showPlayerQuestions = Database.Instance.GetPlayerQuestions(gameManagerScript.GameId, currentPlayerShown, gameManagerScript.GameMode);
            setQuestionFrosting(showPlayerQuestions);
        }
        UpdateButtonsText();
    }

    private void ShowPrevPlayerAnswerLine() {
        if (prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName.Equals(LocalizationManager.Instance.GetText("YOUR"))) {
            currentPlayerShown = signedInName;
        } else {
            currentPlayerShown = prevPlayerButton.GetComponent<AnswerLineInfoPlayerButton>().PlayerName;
            currentPlayerShown = currentPlayerShown.Substring(0, currentPlayerShown.Length - 1);
        }

        if (currentPlayerShown.Equals(signedInName, StringComparison.InvariantCultureIgnoreCase)) {
            List<NewQuestionData> questions = new List<NewQuestionData>();
            foreach (AnswerLineQuestionCard aq in signedInPlayerQuestions) {
                questions.Add(new NewQuestionData(aq.GetAnswerText(), aq.GetQuestionText(), aq.CategoryText, aq.CategoryId, aq.QuestionId, aq.CategoryColor, aq.QuestionSafe));
            }
            setQuestionFrosting(questions);
        } else {
            List<NewQuestionData> showPlayerQuestions = Database.Instance.GetPlayerQuestions(gameManagerScript.GameId, currentPlayerShown, gameManagerScript.GameMode);
            setQuestionFrosting(showPlayerQuestions);
        }
        UpdateButtonsText();
    }

    private void setQuestionFrosting(List<NewQuestionData> questions) {
        ScrollViewScript scrollViewScript = scrollView.GetComponent<ScrollViewScript>();
        scrollViewScript.RemoveEverythingFromAnswerline();
        scrollViewScript.SetQuestionsInAnswerLine(questions);
        if (gameManagerScript.GameMode.Equals(Constants.ONLINE)) {
            if (Database.Instance.GetSignedInUser().Value.Equals(currentPlayerShown, StringComparison.InvariantCultureIgnoreCase)) {
                scrollViewScript.SetQuestionsFrosted(false);
            } else {
                scrollViewScript.SetQuestionsFrosted(true);
            }
        } else {
            if (currentPlayerShown.Equals(Database.Instance.GetCurrentPlayer(gameManagerScript.GameId, gameManagerScript.GameMode), StringComparison.InvariantCultureIgnoreCase)) {
                scrollViewScript.SetQuestionsFrosted(false);
            } else {
                scrollViewScript.SetQuestionsFrosted(true);
            }
        }
    }

    public String getCurrentPlayerShown() {
        return currentPlayerShown;
    }
}
