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 localGamesPanelTitle;
    public Transform onlineGamesPanelTitle;

    public GameObject localGamePrefab;
    public GameObject onlineGamePrefab;
    public GameObject finishedGamePrefab;

    private int loggedInUserId;
    private DateTime lastPlayedLocal;
    private DateTime lastPlayedOnline;

    private void Start() {
        startNewGameButton.onClick.AddListener(StartNewGameAction);
        quitButton.onClick.AddListener(() => { Application.Quit(); });
        
        GetGames();
        UpdateOnlineGamesLists();
        if (lastPlayedLocal > lastPlayedOnline) {
            localGamesPanelTitle.GetComponent<GamesScrollController>().expandThis(localGamesPanelTitle.name);
        } else {
            onlineGamesPanelTitle.GetComponent<GamesScrollController>().expandThis(onlineGamesPanelTitle.name);
        }
    }


    private void Awake() {
        GetGames();
        UpdateOnlineGamesLists();
        if (lastPlayedLocal > lastPlayedOnline) {
            localGamesPanelTitle.GetComponent<GamesScrollController>().expandThis(localGamesPanelTitle.name);
        } else {
            onlineGamesPanelTitle.GetComponent<GamesScrollController>().expandThis(onlineGamesPanelTitle.name);
        }
    }

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

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

        int onlineIndex = 1;
        int finishedGamesIndex = 1;
        if (checkInternetConnection()) {
            List<OnlineGameScript> onlineGames = OnlineDatabase.Instance.GetOnlineGames(loggedInUser.Key, loggedInUser.Value, onlineGamePrefab);
            if (onlineGames != null) {
                foreach (OnlineGameScript ogs in onlineGames) {
                    DateTime.TryParse(ogs.LastPlayedDate, out DateTime onlineLastPlayedDate);
                    if (lastPlayedOnline == null || onlineLastPlayedDate > lastPlayedOnline) {
                        lastPlayedOnline = onlineLastPlayedDate;
                    }
                    if (ogs.GameStatus.Equals("DECLINED")) {
                        ogs.transform.SetParent(finishedGamesList, false);
                        ogs.transform.SetSiblingIndex(finishedGamesIndex++);
                    } else {
                        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) {
            DateTime.TryParse(lgs.LastPlayedDate, out DateTime localLastPlayedDate);
            if (lastPlayedLocal == null || localLastPlayedDate > lastPlayedLocal) {
                lastPlayedLocal = localLastPlayedDate;
            }
            if (lgs.FinishedDate.Equals("")) {
                lgs.transform.SetParent(localGamesList.transform, false);
                lgs.transform.SetSiblingIndex(localIndex++);
            } else {
                lgs.DestroyStartButton();
                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 StartNewGameAction() {
        SceneManager.LoadScene("NewGame");
    }

    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);
    }
}
