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

public class GameInfoScript : MonoBehaviour {

    public Button cancelButton;
    public Button acceptButton;

    public GameObject playerInfoPrefab;

    public Transform playersPanel;
    public Transform gameSettingsPanel;

    private int gameId;
    private int questionTimer;

    // Start is called before the first frame update
    void Start() {
        cancelButton.onClick.AddListener(Hide);
        acceptButton.onClick.AddListener(OpenGame);
    }


    // Update is called once per frame
    void Update() {

    }

    internal void SetOnlineData(OnlineGameScript onlineGameScript) {
        String currentPlayer = Database.Instance.GetSignedInUser().Value;
        gameId = onlineGameScript.GetId();
        questionTimer = onlineGameScript.AnswerTimer;
        foreach (KeyValuePair<string, string> player in onlineGameScript.PlayerInfos) {
            GameObject slp = Instantiate(playerInfoPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
            OnlinePlayerInfoScript opi = slp.GetComponent<OnlinePlayerInfoScript>();
            opi.GameId = gameId;
            opi.SetPlayerName(player.Key);
            if (currentPlayer.Equals(player.Key, StringComparison.InvariantCultureIgnoreCase) && player.Value.Equals("WAITING")) {
                opi.ShowDecitionButtons();
            } else {
                opi.SetPlayerStatus(player.Value);
            }

            opi.transform.SetParent(playersPanel, false);
        }

        acceptButton.enabled = false;
        acceptButton.interactable = false;
        if ("ACTIVE".Equals(onlineGameScript.GameStatus)) {
            acceptButton.enabled = true;
            acceptButton.interactable = true;
        }
    }

    private void OpenGame() {
        PlayerPrefs.SetString("GameMode", "Online");
        PlayerPrefs.SetInt("GameId", gameId);
        PlayerPrefs.SetInt("QuestionTimer", questionTimer);
        SceneManager.LoadSceneAsync("narKampen");
    }

    public void Show() {
        CanvasGroup cg = this.GetComponent<CanvasGroup>();
        cg.alpha = 1;
        cg.interactable = true;
        cg.blocksRaycasts = true;
    }

    public void Hide() {
        CanvasGroup cg = this.GetComponent<CanvasGroup>();
        cg.alpha = 0;
        cg.interactable = false;
        cg.blocksRaycasts = false;

        foreach (OnlinePlayerInfoScript opis in playersPanel.GetComponentsInChildren<OnlinePlayerInfoScript>()) {
            Destroy(opis);
            Destroy(opis.gameObject);
        }

        GameObject.Find("Main Panel").GetComponent<MainMenu>().UpdateOnlineGamesLists();
    }
}
