using LightReflectiveMirror;
using Mirror;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class loadingScreen : MonoBehaviour
{
    public string sceneName;
    public RectTransform loadingWheel;
    public RectTransform loadingProgress;
    CanvasGroup canvasGroup;

    private LightReflectiveMirrorTransport _LRM;

    public void show()
    {
        canvasGroup.blocksRaycasts = canvasGroup.interactable = true;
    }

    public void hide()
    {
        canvasGroup.blocksRaycasts = canvasGroup.interactable = false;
    }

    void Start()
    {
        DontDestroyOnLoad(gameObject);
        canvasGroup = GetComponent<CanvasGroup>();

        if (_LRM == null)
        {
            _LRM = (LightReflectiveMirrorTransport)Transport.activeTransport;
        }

    }
    AsyncOperation loadingOperation;
    // Update is called once per frame
    void Update()
    {
        loadingWheel.Rotate(new Vector3(0, 0, 1f));

        if (loading)
        {
            loadingProgress.sizeDelta = new Vector2(165f * loadingOperation.progress, loadingProgress.sizeDelta.y);
        }

        if (canvasGroup.interactable && canvasGroup.alpha < 1)
        {
            canvasGroup.alpha += 0.01f;
        }
        if(!canvasGroup.interactable && canvasGroup.alpha > 0)
        {
            canvasGroup.alpha -= 0.01f;
        }
    }

    
    bool loading = false;
    public bool isHost= true;
    public async void load()
    {
        show();
        await Task.Delay(1000);
        loading = true;
        loadingProgress.sizeDelta = new Vector2(0, loadingProgress.sizeDelta.y);
        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
        loadingOperation = SceneManager.LoadSceneAsync(sceneName);
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (loading)
        {
           // hide();
           if(isHost){host();}else{join();}
            
            loading = false;
        }
    }
    public string serverName;
    public bool isPublic;
    
    void host()
    {
        _LRM.serverName = serverName;
        _LRM.extraServerData = sceneName;
        _LRM.isPublicServer = isPublic;

        _LRM.ServerStart();
        NetworkManager.singleton.StartHost();
    }

    void join()
    {
        NetworkManager.singleton.networkAddress = serverName;
        NetworkManager.singleton.StartClient();
    }
}
