using UnityEngine;
using GeoSus.Client;
using Subsystems;
using System.Threading;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using TMPro;
/*
    GameManager - hlavní třida pro správu hry
    GameManager_Network - subsystém pro správu komunikace se serverem
    GameManager_Game - subsystém pro správu logiky hry (sabotáže, tasky, atd.)
    GameManager_Map - subsystém pro správu mapy a prostředí
    GameManager_Input - subsystém pro správu vstupu od hráče
    GameManager_UI - subsystém pro správu uživatelského rozhraní
    GamaManager_Stats - subsystém pro správu statistik pro server
 */
public class GameManager : MonoBehaviour
{
    [Header("Subsystems")]
    protected GameManager_Network networkSubsystem;
    protected GameManager_UI uiSubsystem;


    protected GameClient gameClient;
    [Header("Player Info")]
    public string displayName;

    [Header("UI Elements")]
    public Canvas JoinCreateLobby;
    public Canvas InLobby;

    void Start()
    {
        DontDestroyOnLoad(this);
        if (displayName == null || displayName == "")
        {
            displayName = "Player_" + Random.Range(1000, 9999).ToString();
        }
        gameClient = new GameClient(GenerateUUID(), /*displayName*/ GenerateUsername());
        uiSubsystem = new GameManager_UI(gameClient, JoinCreateLobby, InLobby);
        networkSubsystem = new GameManager_Network(gameClient);
        networkSubsystem.OpenConection();
    }
    private void Update()
    {
        if (gameClient.CurrentLobbyState != null)
        {
            uiSubsystem.UpdateLobbyUI();

        }
    }


    protected string GenerateUUID()
    {
        string UUID = System.Guid.NewGuid().ToString();
        Debug.Log(UUID);
        return UUID;
    }
    protected string GenerateUsername()
    {
        string Username = Random.Range(0,10).ToString() + Random.Range(0, 10).ToString() + Random.Range(0, 10).ToString() + Random.Range(0, 10).ToString();
        Debug.Log(Username);
        return Username;
    }
    public void CreateLobbyButton()
    {
        networkSubsystem.CrateLobby(50.0755, 14.4378);
    }
    public void JoinLobbyButton()
    {
        TMP_InputField joinCode = JoinCreateLobby.transform.Find("InputCode").GetComponent<TMP_InputField>();
        if (joinCode.text != null && joinCode.text != "")
        {
            networkSubsystem.JoinLobby(joinCode.text);
        }
        else
        {
            Debug.Log("Join code is empty!");
        }
    }
    public void LeaveLobbyButton()
    {
        networkSubsystem.LeaveLobby();
    }
    void OnApplicationQuit()
    {
        gameClient.Disconnect();
    }
}
