using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour {

    public Button startNewGameButton;
    public Button quitButton;
    public Transform activeGamesPanel;
    public Transform newGamePanel;
    public Slider gameTypeSlider;
    public InputField localPlayers;
    public GameObject playerSettingPrefab;
    public Button startLocalGameButton;
    public Button backButton;
    public InputField winningCountInputField;
    public InputField timeToAnswerInputField;
    public GameObject localGamePrefab;
    public GameObject onlineGamePrefab;
    public GameObject finishedGamePrefab;

    private int loggedInUserId;

    private void Start() {
        startNewGameButton.onClick.AddListener(StartNewGameAction);
        backButton.onClick.AddListener(BackButtonAction);

        quitButton.onClick.AddListener(() => { Application.Quit(); });
        gameTypeSlider.onValueChanged.AddListener(SliderChoice);
        localPlayers.onValueChanged.AddListener(LocalPlayersAction);
        startLocalGameButton.onClick.AddListener(StartLocalGame);
    }


    private void Awake() {
        GetGames();
        UpdateOnlineGamesLists();
    }

    public void UpdateOnlineGamesLists() {
        KeyValuePair<int, string> loggedInUser = Database.Instance.GetSignedInUser();
        Transform onlineGamesList = GameObject.Find("OnlineGamesList").transform;

        foreach (OnlineGameScript ogs in onlineGamesList.GetComponentsInChildren<OnlineGameScript>()) {
            Destroy(ogs);
            Destroy(ogs.gameObject);
        }

        int onlineIndex = 1;
        if (checkInternetConnection()) {
            List<OnlineGameScript> onlineGames = OnlineDatabase.Instance.GetOnlineGames(loggedInUser.Key, loggedInUser.Value, onlineGamePrefab);
            if (onlineGames != null) {
                foreach (OnlineGameScript ogs in onlineGames) {
                    ogs.transform.SetParent(onlineGamesList, false);
                    ogs.transform.SetSiblingIndex(onlineIndex++);
                }
            }
        } else {
            // Display no internet information
            Debug.Log("No internet");
        }
    }

    private void GetGames() {
        KeyValuePair<int, string> loggedInUser = Database.Instance.GetSignedInUser();
        List<LocalGameScript> localGames = Database.Instance.GetLocalGames(localGamePrefab);
        Transform localGamesList = GameObject.Find("LocalGamesList").transform;
        Transform finishedGamesList = GameObject.Find("FinishedGamesList").transform;

        foreach(LocalGameScript lgs in localGamesList.GetComponentsInChildren<LocalGameScript>()) {
            Destroy(lgs);
            Destroy(lgs.gameObject);
        }

        foreach (LocalGameScript lgs in finishedGamesList.GetComponentsInChildren<LocalGameScript>()) {
            Destroy(lgs);
            Destroy(lgs.gameObject);
        }

       
        int localIndex = 1;
        int finishedIndex = 1;
        foreach (LocalGameScript lgs in localGames) {
            if (lgs.FinishedDate.Equals("")) {
                lgs.transform.SetParent(localGamesList.transform, false);
                lgs.transform.SetSiblingIndex(localIndex++);
            } else {
                lgs.DisableStartButton();
                lgs.transform.SetParent(finishedGamesList.transform, false);
                lgs.transform.SetSiblingIndex(finishedIndex++);
            }

        }

    }

    private bool checkInternetConnection() {
        bool internetConnectivityActive;
        UnityWebRequest www = UnityWebRequest.Get("http://google.com");
        www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError) {
            internetConnectivityActive = false;
        } else {
            internetConnectivityActive = true;
        }

        return internetConnectivityActive;
    }

    private void LocalPlayersAction(string value) {
        Transform settingsPanel = GameObject.Find("PlayerSettingsPanel").transform;
        PlayerSetting[] players = settingsPanel.GetComponentsInChildren<PlayerSetting>();
        int playersCount = players.Length;
        if (!Int32.TryParse(value, out int newValue)) {
            newValue = 1;
        }
        if (newValue < 1) {
            newValue = 1;
        }

        if (playersCount < newValue) { // add new PlayerSettings
            for (int i = playersCount; i < newValue; i++) {
                GameObject go = Instantiate(playerSettingPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
                PlayerSetting ps = go.GetComponent<PlayerSetting>();
                ps.SetPlayerText(i + 1);
                ps.SetPlayerName(i + 1);

                ps.transform.SetParent(settingsPanel, false);
                ps.transform.SetSiblingIndex(i + 1);
            }
        } else if (playersCount > newValue) { // remove playersettings from end
            for (int i = playersCount; i > newValue; i--) {
                PlayerSetting toDestroy = settingsPanel.GetChild(i - 1).GetComponent<PlayerSetting>();
                Destroy(toDestroy.gameObject);
            }
        }
        ScrollRect scrollPanel = GameObject.Find("LacalPlayersScrollView").GetComponent<ScrollRect>();
        scrollPanel.verticalNormalizedPosition = 0f;
    }

    private void StartNewGameAction() {
        ShowNewGamePanel();
    }

    private void BackButtonAction() {
        HideNewGamesPanel();
    }

    private void SetPanelVisibility(string panelName, bool isVisible) {
        CanvasGroup panelCG= GameObject.Find(panelName).gameObject.GetComponent<CanvasGroup>();
        panelCG.alpha = (isVisible?1f:0f);
        panelCG.interactable = (isVisible?true:false);
        panelCG.blocksRaycasts = (isVisible ? true : false);
    }

    public void HideNewGamesPanel() {
        SetPanelVisibility("LocalGameSettings", false);
        SetPanelVisibility("OnlineGameSettings", false);

        SetPanelVisibility("GameType", false);

        activeGamesPanel.gameObject.GetComponent<CanvasGroup>().alpha = 1;
        activeGamesPanel.gameObject.GetComponent<CanvasGroup>().blocksRaycasts = true;

        SetPanelVisibility("Games", true);
        CanvasGroup startButtonCanvasGroup = startNewGameButton.GetComponent<CanvasGroup>();
        CanvasGroup backButtonCanvasGroup = backButton.GetComponent<CanvasGroup>();
        
        startButtonCanvasGroup.interactable = true;
        startButtonCanvasGroup.blocksRaycasts = true;
        startButtonCanvasGroup.alpha = 1f;

        backButtonCanvasGroup.interactable = false;
        backButtonCanvasGroup.blocksRaycasts = false;
        backButtonCanvasGroup.alpha = 0f;
    }

    private void ShowNewGamePanel() {
        SetPanelVisibility("LocalGameSettings", false);
        SetPanelVisibility("OnlineGameSettings", false);

        SetPanelVisibility("GameType", true);
        SetPanelVisibility("Games", false);


        activeGamesPanel.gameObject.GetComponent<CanvasGroup>().alpha = 0;
        activeGamesPanel.gameObject.GetComponent<CanvasGroup>().blocksRaycasts = false;

        CanvasGroup startButtonCanvasGroup = startNewGameButton.GetComponent<CanvasGroup>();
        CanvasGroup backButtonCanvasGroup = backButton.GetComponent<CanvasGroup>();

        startButtonCanvasGroup.interactable = false;
        startButtonCanvasGroup.blocksRaycasts = false;
        startButtonCanvasGroup.alpha = 0f;

        backButtonCanvasGroup.interactable = true;
        backButtonCanvasGroup.blocksRaycasts = true;
        backButtonCanvasGroup.alpha = 1f;
    }

    private void SliderChoice(float arg) {
        CanvasGroup localGameSettings = GameObject.Find("LocalGameSettings").gameObject.GetComponent<CanvasGroup>();
        CanvasGroup onlineGameSettings = GameObject.Find("OnlineGameSettings").gameObject.GetComponent<CanvasGroup>();
        if (arg == 0) { // Local game
            SetPanelVisibility("LocalGameSettings", true);
            SetPanelVisibility("OnlineGameSettings", false);

            LocalPlayersAction("1");
        } else if (arg == 2) { // Online game
            SetPanelVisibility("LocalGameSettings", false);
            SetPanelVisibility("OnlineGameSettings", true);
        } else { // No choice, hide all
            SetPanelVisibility("LocalGameSettings", false);
            SetPanelVisibility("OnlineGameSettings", false);
        }
    }

    private void StartLocalGame() {
        Database.Instance.SetLocalOrOnline("Local");
        List<string> playerNames = new List<string>();

        if (!Int32.TryParse(winningCountInputField.text, out int winningCount)) {
            winningCount = 10;
        }
        if (!Int32.TryParse(localPlayers.text, out int players)) {
            players = 1;
        }
        if (!Int32.TryParse(timeToAnswerInputField.text, out int questionTimer)) {
            questionTimer = 20;
        }

        int gameId = Database.Instance.SetupNewLocalGame(winningCount, players, questionTimer);

        Transform settingsPanel = GameObject.Find("PlayerSettingsPanel").transform;
        PlayerSetting[] playerSettings = settingsPanel.GetComponentsInChildren<PlayerSetting>();

        for (int i = 0; i < playerSettings.Length; i++) {
            string playerName = playerSettings[i].GetComponent<PlayerSetting>().nameInput.text;
            playerNames.Add(playerName);
        }

        Database.Instance.LinkPlayersToLocalGame(playerNames, gameId);

        PlayerPrefs.SetString("GameMode", "Local");
        PlayerPrefs.SetInt("GameId", gameId);
        PlayerPrefs.SetInt("QuestionTimer", questionTimer);
        SceneManager.LoadSceneAsync("narKampen");
    }
}
