using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Game.Plugins.App;
using Game.Script.battle.mode;
using Game.Script.battle.mode.GWorldSync01ModeScript;
using Script.battle;
using UnityEngine;

public class GWorldSync01UI : MonoBehaviour
{

    // public Camera cam;
    public LayerMask mask;
    
    //获取模式
    private GWorldSync01Mode Mode => GBattleModeManager.Instance.GetMode<GWorldSync01Mode>();
    
    //获取相机
    private Camera Cam => (Mode != null ? Mode.GetComponentInChildren<Camera>() : null);
    
    //当前控制的玩家
    public long playerId = 0;
    
    //添加玩家
    public void AddPlayer(Boolean isRobot = false)
    {
        //添加玩家
        Mode.NInput.Key = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        Mode.NInput.IsAdd = true;
        Mode.NInput.IsRobot = isRobot;
        if (!isRobot)
        {
            playerId = Mode.NInput.Key;
        }
    }
    
    //点击加入人机
    public void OnClickJoinRobot()
    {
        this.AddPlayer(true);
    }
    
    //点击加入游戏
    public void OnClickJoinGame()
    {
        this.AddPlayer();
    }
    
    //点击场景
    public void OnClickScene()
    {
        
        var players = Mode.GetComponentsInChildren<PlayerBot>();
        
        foreach (var playerBot in players.Where(item => item.key == playerId))
        {
            
            Vector3 newPosition = Vector3.zero;
            bool positionFound = false;
        
            RaycastHit hit;
            if (Cam.pixelRect.Contains(Input.mousePosition) && Physics.Raycast(Cam.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, mask)) {
                newPosition = hit.point;
                positionFound = true;
            }
        
            if (positionFound) {
                playerBot.NInput.IsPos = true;
                playerBot.NInput.x = newPosition.x;
                playerBot.NInput.y = newPosition.y;
                playerBot.NInput.z = newPosition.z;
                // if (onlyOnDoubleClick) {
                //     for (int i = 0; i < ais.Length; i++) {
                //         if (ais[i] != null) ais[i].SearchPath();
                //     }
                // }
            }
            
        }
    }

    private void Update()
    {
        // if(this.Cam != null)
        //     this.Cam.enabled = !App.Sync.IsLoop;
    }
}
