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 InputField winningCountInputField;
    public InputField timeToAnswerInputField;
    public GameObject localGamePrefab;
    public GameObject onlineGamePrefab;

    private Database db;

    private readonly string gamesPostUrl = "nordh.xyz/narKampen/dbFiles/Games.php?";

    private void Start() {
        // GetGames();
        startNewGameButton.onClick.AddListener(StartNewGameAction);
        quitButton.onClick.AddListener(() => { Application.Quit(); });
        gameTypeSlider.onValueChanged.AddListener(SliderChoice);
        localPlayers.onValueChanged.AddListener(LocalPlayersAction);
        startLocalGameButton.onClick.AddListener(StartLocalGame);

        db = GameObject.Find("Main Panel").GetComponent<Database>();

        GetGames();
    }

    private void GetGames() {
        int loggedInUserId = PlayerPrefs.GetInt("UserId");
        List<LocalGameScript> localGames = db.GetLocalGames(localGamePrefab);
        Transform localGamesList = GameObject.Find("LocalGamesList").transform;

        int i = 1;
        foreach (LocalGameScript lgs in localGames) {
            lgs.transform.SetParent(localGamesList.transform);
            lgs.transform.SetSiblingIndex(i++);

        }
        if (checkInternetConnection()) {
            db.GetOnlineGames(loggedInUserId);
        } else {
            // Display no internet information
            Debug.Log("No internet");
        }
    }

    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);
                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 IEnumerator GetGamesFromServer() {
        string postUrl = gamesPostUrl + "userId=" + PlayerPrefs.GetInt("UserId");

        UnityWebRequest www = UnityWebRequest.Get(postUrl);

        yield return www.SendWebRequest();
    }

    private void StartNewGameAction() {
        StartNewGamePanelChange();
    }

    private void StartNewGamePanelChange() {
        RectTransform activeGamesRect = activeGamesPanel.GetComponent<RectTransform>();
        RectTransform newGamesRect = newGamePanel.GetComponent<RectTransform>();

        startNewGameButton.gameObject.SetActive(false);
        Color startButtonColor = startNewGameButton.GetComponent<Image>().color;
        float activeGamesPanelheight = activeGamesRect.rect.height;

        GameObject.Find("GameType").gameObject.GetComponent<CanvasGroup>().alpha = 1;
        activeGamesPanel.gameObject.GetComponent<CanvasGroup>().alpha = 0;
        activeGamesPanel.gameObject.GetComponent<CanvasGroup>().blocksRaycasts = false;

        CanvasGroup localPanelCanvas = GameObject.Find("LocalGamesPanel").GetComponent<CanvasGroup>();
        CanvasGroup onlinePanelCanvas = GameObject.Find("OnlineGamesPanel").GetComponent<CanvasGroup>();
        localPanelCanvas.alpha = 0;
        localPanelCanvas.blocksRaycasts = false;
        onlinePanelCanvas.alpha = 0;
        onlinePanelCanvas.blocksRaycasts = false;
    }

    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
            localGameSettings.alpha = 1;
            localGameSettings.blocksRaycasts = true;
            onlineGameSettings.alpha = 0;
            onlineGameSettings.blocksRaycasts = false;
            LocalPlayersAction("1");
        } else if (arg == 2) { // Online game
            onlineGameSettings.alpha = 1;
            onlineGameSettings.blocksRaycasts = true;
            localGameSettings.alpha = 0;
            localGameSettings.blocksRaycasts = false;
        } else { // No choice, hide all
            localGameSettings.alpha = 0;
            onlineGameSettings.alpha = 0;
            localGameSettings.blocksRaycasts = false;
            onlineGameSettings.blocksRaycasts = false;
        }
    }

    private void StartLocalGame() {
        db = GameObject.Find("Main Panel").GetComponent<Database>();
        db.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 = db.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);
        }

        db.LinkPlayersToLocalGame(playerNames, gameId);
 
        PlayerPrefs.SetInt("GameId", gameId);
        SceneManager.LoadSceneAsync("narKampen");
    }
}
