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

public struct ReadyInfo
{
    public long RoomId;
    public long UserId;
    public bool IsReady;
}
public class ReadyToggle : MonoBehaviour
{
    public Text ErrorText;
    public Text Lable;
    public Image MaskImage;
    private MainPanel mainPanel;
    // Use this for initialization
    void Start()
    {
        mainPanel = transform.parent.parent.Find("MainPanel").GetComponent<MainPanel>();
        GetComponent<Toggle>().onValueChanged.AddListener(toggleChange);
    }

    private void toggleChange(bool value)
    {
        //如果是房间创建者
        if (CurrentUserInfo.room.Owner.UserInfo.Id == CurrentUserInfo.mySelf.Id)
        {
            //判断除了房主是否都准备
            if (mainPanel.IsAllReadyExcludeOwner())
            {
                CurrentUserInfo.room.Owner.IsReady = true;
                MainPanel.Instance.UpdateUserStateFunction(CurrentUserInfo.room.Owner.UserInfo.Id, CurrentUserInfo.room.Owner.IsReady);
                
                NetworkManager.Default.SendAsync("BATTLE_READY_SYNC",new KeyValuePair<long,bool>(CurrentUserInfo.room.Id,CurrentUserInfo.room.IsDrillStart));
                ////清除聊天内容
                //ChatManager.Instance.ClearPublicChatMsgs();
            }
            else
            {
                StartCoroutine(ErrorTextDisplay());
            }
        }
        else
        {
            //一般用户
            MaskImage.gameObject.SetActive(value);
            
            Lable.text = !value ? "开始/准备" : "取消准备";
            readyStateChange(value);
        }

    }

   
    void readyStateChange(bool value)
    {
        ReadyInfo readyUser = new ReadyInfo
        {
            RoomId = CurrentUserInfo.room.Id,
            UserId = CurrentUserInfo.mySelf.Id,
            IsReady =value
        };
        NetworkManager.Default.SendAsync("ROOM_READY_SYNC",readyUser);

    }
    IEnumerator ErrorTextDisplay()
    {
        //ErrorText.gameObject.SetActive(true);
        ErrorText.text = "有人尚未准备!";
        GetComponent<Toggle>().interactable = false;
        yield return new WaitForSeconds(1f);
        //ErrorText.gameObject.SetActive(false);
        ErrorText.text = "";
        GetComponent<Toggle>().interactable = true;
    }
}