using AdamSync;
using System;
using System.Collections;
using System.Collections.Generic;
using Tenkoku.Core;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public SyncPlayerTransform playerTransformPrefab;
    public Transform spawnPos;
    public List<ulong> userIds = new List<ulong>();
    public TenkokuModule tenkokuModule;
    public List<ModelInfo> modelsInfo = new List<ModelInfo>();
    public Transform dviceContent;
    public GameObject wrjDrag;
    public GameObject ldDrag;
    public GameObject hpDrag;
    // Start is called before the first frame update
    private void Awake()
    {
        SyncCreateRoom.getroomusersRequset += OnGetRoomUsers;
        SyncCreateRoom.send2roomRequset += OnOtherPlayerOnline;
        SyncPlayerTransform spt = Instantiate(playerTransformPrefab);
        spt.gameObject.SetActive(true);
        spt.gameObject.transform.position = spawnPos.position;
        spt.gameObject.transform.eulerAngles = spawnPos.eulerAngles;
        spt.SetPlayerInfo(ulong.Parse(GlobalFlag.currentUser.user_id), GlobalFlag.currentUser.login_name, ulong.Parse(GlobalFlag.roomID), true);
        //0 red  1 blue
        if (UIBootstrap.Instance.GetRoleByIDPracticeId(GlobalFlag.practiceSeatId) == "0")
        {
            spt.GetComponent<Camera>().cullingMask = ~(1 << 11);
            GameObject wrj = Instantiate(wrjDrag, dviceContent);
        }
        else
        {
            spt.GetComponent<Camera>().cullingMask = ~(1 << 12);
            GameObject ld = Instantiate(ldDrag, dviceContent);
            GameObject hp = Instantiate(hpDrag, dviceContent);
        }
        userIds.Add(ulong.Parse(GlobalFlag.currentUser.user_id));
        tenkokuModule.mainCamera = spt.transform;
    }

    public void Start()
    {
        SetWeatherValue();
        SetModelValue();
        string msg = "getroomusers ";
        _ = SyncCreateRoom.SendMessageAsync(msg);
    }




    public void OnOtherPlayerOnline(string msg)
    {
        StopCoroutine(WaitSpawn(msg));
        StartCoroutine(WaitSpawn(msg));
    }

    private IEnumerator WaitSpawn(string msg)
    {
        yield return new WaitForSeconds(0.5f);
        Debug.Log(msg);
        string[] data = msg.Split(',');
        switch (data[0])
        {
            case "online":
                ulong userId = ulong.Parse(data[1]);
                if (!userIds.Contains(userId))
                {
                    SyncPlayerTransform spt = Instantiate(playerTransformPrefab);
                    spt.gameObject.SetActive(true);
                    spt.gameObject.transform.position = spawnPos.position;
                    spt.gameObject.transform.eulerAngles = spawnPos.eulerAngles;
                    spt.SetPlayerInfo(ulong.Parse(data[1]), data[2], ulong.Parse(data[3]), false);
                }
                break;
            case "offline":
                break;
        }
    }

    private void OnGetRoomUsers(string obj)
    {
        if (string.IsNullOrWhiteSpace(obj)) return;
        string[] data = obj.Split(';');
        Debug.Log("datas=" + data[0]);
        for (int i = 0; i < data.Length; i++)
        {
            int index = i;
            string[] userInfo = data[index].Split(',');
            if (!userIds.Contains(ulong.Parse(userInfo[0])))
            {
                SyncPlayerTransform spt = Instantiate(playerTransformPrefab);
                spt.gameObject.SetActive(true);
                spt.SetPlayerInfo(ulong.Parse(userInfo[0]), userInfo[1], ulong.Parse(userInfo[2]), false);
                spt.transform.position = new Vector3(spawnPos.position.x + index * 0.5f, spawnPos.position.y, spawnPos.position.z + index * 0.5f);
                spt.transform.eulerAngles = spawnPos.eulerAngles;
                userIds.Add(ulong.Parse(userInfo[0]));
            }
        }
        string msg = $"send2room online,{ulong.Parse(GlobalFlag.currentUser.user_id)},{ GlobalFlag.currentUser.login_name},{ulong.Parse(GlobalFlag.roomID)}";
        _ = SyncCreateRoom.SendMessageAsync(msg);
    }


    public void OnBack()
    {
        SceneManager.LoadScene("TEstSync");
    }

    public void SetWeatherValue()
    {
        tenkokuModule.weather_RainAmt = Mathf.Lerp(0f, 1f, float.Parse(UIBootstrap.Instance.currentSceneInfo.data.EnvRain));
        tenkokuModule.weather_SnowAmt = Mathf.Lerp(0f, 1f, float.Parse(UIBootstrap.Instance.currentSceneInfo.data.EnvSnow));
        tenkokuModule.weather_WindAmt = Mathf.Lerp(0f, 1f, float.Parse(UIBootstrap.Instance.currentSceneInfo.data.EnvWindSpeed));
        tenkokuModule.weather_WindDir = Mathf.Lerp(0f, 1f, float.Parse(UIBootstrap.Instance.currentSceneInfo.data.EnvWindDir));
        tenkokuModule.weather_lightning = Mathf.Lerp(0f, 1f, float.Parse(UIBootstrap.Instance.currentSceneInfo.data.EnvLight));
    }



    public void SetModelValue()
    {
        string info = UIBootstrap.Instance.currentSceneInfo.data.DeviceContent;
        Debug.Log(info);
        if (info.Length > 0 &&string .IsNullOrWhiteSpace(info))
        {
            modelsInfo = Jsonanalyze.FromJson<List<ModelInfo>>(info);
            for (int i = 0; i < modelsInfo.Count; i++)
            {
                GameObject obj = Resources.Load<GameObject>(modelsInfo[i].str);
                GameObject go = Instantiate(obj);
                go.transform.position = new Vector3(float.Parse(modelsInfo[i].x.ToString()), float.Parse(modelsInfo[i].y.ToString()), float.Parse(modelsInfo[i].z.ToString()));
            }
        }
    }



    private void OnDisable()
    {
        Debug.Log("OnDisable");
        SyncCreateRoom.getroomusersRequset -= OnGetRoomUsers;
        SyncCreateRoom.send2roomRequset -= OnOtherPlayerOnline;
    }

}

[Serializable]
public class ModelInfo
{
    public string str;
    public double x;
    public double y;
    public double z;
}