using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchAndObjJudge : MonoBehaviour {

    ScreenTouch screenTouch;
    [SerializeField] GameObject[] playerObj;//タッチ可能なプレイヤー

    List<GameObject> touchPlayer = new List<GameObject>();//タッチしたプレイヤー保存用
    List<float> touchDistance = new List<float>();        //タッチしたプレイヤーとマウス座標の格納
    GameObject operatingPlayer;//タッチ判定後、タッチしたと判定されたプレイヤー格納

    float playerRangeX = 0f;//タッチ可能領域X
    float playerRangeY = 0f;//タッチ可能領域Y


	// Use this for initialization
	void Start () {
        screenTouch = GetComponent<ScreenTouch>();   

        //プレイヤーオブジェクトを最低1つは追加する
		if(playerObj[0] == null)
        {
            playerObj[0] = GameObject.Find("Player").transform.FindChild("steel").gameObject;
        }

        //スクリーンの大きさに合わせてタッチ可能領域を調整
        playerRangeX = Screen.width / 10f;
        playerRangeY = Screen.height / 4f;
        
        Debug.Log("Width = " + Screen.width);
        Debug.Log("Height = " + Screen.height);
        Debug.Log("playerRangeX = " + playerRangeX);
        Debug.Log("playerRangeY = " + playerRangeY);
        
    }

    //=========================================================
    //プレイヤーのタッチ判定の範囲内をタッチしたかの判定
    //=========================================================
    public bool PlayerTouchJudge(Vector2 mousePosition)
    {
        //Debug.Log("Player = " + playerObj[0]);
        bool isPlayerTouch = false;
		//事前に配列に登録しておいたタッチ可能なプレイヤーの人数分処理する
        for (int i = 0; i < playerObj.Length; i++) {
            playerObj[i].GetComponent<CPU>().playerControl = false;//コントロールをCPUにいったん戻す
            //Debug.Log("MousePosition = " + mousePosition);
            Vector2 playerScreenPos = Camera.main.WorldToScreenPoint(playerObj[i].transform.FindChild("steel").gameObject.transform.position);
            if (mousePosition.x >= playerScreenPos.x - playerRangeX &&
                mousePosition.x <= playerScreenPos.x + playerRangeX &&
                mousePosition.y >= playerScreenPos.y - playerRangeY &&
                mousePosition.y <= playerScreenPos.y + playerRangeY)
            {
                //Debug.Log("playerScreenPos.x - 50 = " + (playerScreenPos.x - playerRangeX));
                //Debug.Log("playerScreenPos.x + 50 = " + (playerScreenPos.x + playerRangeX));
                //Debug.Log("playerScreenPos.y - 70 = " + (playerScreenPos.y - playerRangeY));
                //Debug.Log("playerScreenPos.y + 70 = " + (playerScreenPos.y + playerRangeY));
                Debug.Log("プレイヤーをタッチした" + playerObj[i]);
                float distance = Vector2.Distance(playerScreenPos, mousePosition);
                addToTouchPlayer(playerObj[i], distance);
                isPlayerTouch = true;
            }
        }
        //プレイヤーをタッチしている時
        if (isPlayerTouch)
        {
            touchPlayerJudge();//どのプレイヤーをタッチしたかの判定
        }
        return isPlayerTouch;
    }

    //タッチ判定領域内をタッチされたプレイヤーを追加する
    void addToTouchPlayer(GameObject playerObj, float distance)
    {
        //Debug.Log("addToTouchPlayer");
        touchPlayer.Add(playerObj);
        touchDistance.Add(distance);
    }

    //追加されたリスト内で、どのプレイヤーにタッチした位置が近いかを判定し、それでタッチしたプレイヤーを判定
    void touchPlayerJudge()
    {
		//Debug.Log("touchPlayerJudge");
		if (touchPlayer.Count == 0) return;
		else if (touchPlayer.Count == 1)
		{
			operatingPlayer = touchPlayer[0];
			Debug.Log(operatingPlayer);
		}
		else
		{
			GameObject candidatePlayer = touchPlayer[0];//タッチしたプレイヤーの候補
			for (int i = 0; i + 1 < touchPlayer.Count; i++)
			{
				if (touchDistance[i] < touchDistance[i + 1])
				{
					candidatePlayer = touchPlayer[i];
				}
				else
				{
					candidatePlayer = touchPlayer[i + 1];
				}
			}
			//この地点でタッチ地点に最も近いプレイヤーが決まっている
			operatingPlayer = candidatePlayer;
            //CPUの操作をプレイヤーの操作へ変える
            operatingPlayer.GetComponent<CPU>().playerControl = true;
			Debug.Log(operatingPlayer);
			touchPlayer.Clear();
		}
    }

    //タッチ機能からタッチしたプレイヤーの判定が渡ってきた後、その名前を返す
    public string objName()
    {
        //Debug.Log(operatingPlayer);
        return operatingPlayer.name;
    }

	//プレイヤーのスクリーン座標(変換した座標)を返す
    public Vector2 getPlayerScreenPoint()
    {
        return Camera.main.WorldToScreenPoint(operatingPlayer.transform.position);
    }

	//Y軸のみ地面の座標で、プレイヤーの位置を返す
	public Vector3 getPlayerMovePos()
	{
		return new Vector3(operatingPlayer.transform.position.x, GameObject.Find("Plane").transform.position.y, operatingPlayer.transform.position.z);
	}
}