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

//タッチ機能、プレイヤーを動かす命令を送るまでの処理

public class ScreenTouch : MonoBehaviour {

    GameManager gmanager;
    SupportScreenTouch support;

    bool isPlayerTouch = false;     //プレイヤーをタッチした
    bool isAnotherPlayerTouch = false;//操作していたプレイヤーと異なるプレイヤーをタッチしたらtrueになる
    bool isPlayerOperation = false;	//プレイヤーをタッチしたのちにドラッグすれば操作したとみなす
    Vector2 touchBeginPos;          //最初にタッチした位置(スクリーン座標)
    string operatingPlayerName = "";//タッチして操作しているプレイヤーの名前
    string hitObjName = "";
    int dragCount = 0;				//ドラッグした時間のカウント(フレーム数)

    // Use this for initialization
    void Start()
    {
        support = GetComponent<SupportScreenTouch>();
        gmanager = GameObject.Find("Manager").GetComponent<GameManager>();
    }

    // Update is called once per frame
    void Update()
    {

        if (!gmanager.IsGamePlayOK()) return;

        MouseScreenTouch();
    }

    //=========================================================
    //マウスでの取得
    //=========================================================
    void MouseScreenTouch()
    {
        if (Input.GetMouseButtonDown(0))
            touchBegin();

        if (!isPlayerTouch) return;
        ///////////////////////////////////////////////////////
        //ここからはプレイヤーを取得しているときの処理
        ///////////////////////////////////////////////////////
        if (Input.GetMouseButton(0))
            drag(Input.mousePosition);

        if (Input.GetMouseButtonUp(0))
            touchOut();
    }

    //=========================================================
    //タッチした瞬間
    //=========================================================
    void touchBegin()
    {
        touchBeginPos = Input.mousePosition;
        //Debug.Log("タッチ開始 MousePosition = " + Input.mousePosition);
        judgeObjectsAndAct(Input.mousePosition);
    }

    //=========================================================
    //ドラッグ中
    //=========================================================
    void drag(Vector2 mousePos)
    {
        dragCount++;
        //一定距離ドラッグしたら移動先を追加し、更新
        if (Vector2.Distance(touchBeginPos, mousePos) >= 30)
        {
            if (isAnotherPlayerTouch)
            {
                //別のプレイヤーのタッチが操作の判定であったため、名前を保存
                setOperationgPlayerName(hitObjName);
                isAnotherPlayerTouch = false;
            }
            //エラー防止のため、Rayが当たったオブジェクトのレイヤー名を確認
            if (support.IsLayerNameToMatch(support.RayHitReturnObj(mousePos), "coat"))
            {
                Vector3 targetPos = support.RayHitReturnHitPoint(mousePos);
				//コートの外をタッチしても追加しないようにする
				if (targetPos.x < 40f && targetPos.x > -40f && targetPos.z < 75f && targetPos.z > -75f)
				{
					Debug.Log("コート上の移動先を追加" + operatingPlayerName);
					movePosAdd(operatingPlayerName, targetPos);
				}
            }
            isPlayerOperation = true;
            //Debug.Log(dragCount);

            //速くドラッグしたら速く動く
            if (dragCount <= 2)
            {
                getScriptPlayer(operatingPlayerName).rewriteMoveSpeed();
            }
            dragCount = 0;
        }
    }

    //=========================================================
    //タッチを離した瞬間
    //=========================================================
    void touchOut()
    {
        GameObject hitObj = support.RayHitReturnObj(Input.mousePosition);//タッチしたオブジェクト
		if (hitObj == null) return;
        //Debug.Log(hitObj.name);
        Vector3 hitPos = support.RayHitReturnHitPoint(Input.mousePosition);//Rayが当たった位置

        //-------------------------------------------------------
        //ここからゴールをタッチした判定、他の味方プレイヤーをタッチした判定を記載していく↓↓
        //-------------------------------------------------------

        bool isGoalTouch = false;

        switch (support.IsLayerNameObj(hitObj))
        {
            case "coat":
				Debug.Log("移動先を追加");
                movePosAdd(operatingPlayerName, hitPos);//タッチを離した瞬間の位置もリストに追加する
                break;
            case "Goal":
                getScriptPlayer(operatingPlayerName).Shoot();
                isGoalTouch = true;
                break;
            default: break;
        }

        //ゴールをタッチしていたら、後のプレイヤーのタッチ判定は行わない
        if (isGoalTouch)
        {
            isGoalTouch = false;
            return;
        }

        //タッチした範囲で取得したプレイヤーが操作していないプレイヤーならパス
        TouchAndObjJudge judge = GetComponent<TouchAndObjJudge>();
        if (judge.PlayerTouchJudge(Input.mousePosition))
        {
            if (hitObjName == "") return;
            string objName = judge.objName();
            GameObject targetObj = GameObject.Find(objName);
            //名前が異なり、チームが一致すればパス
            if(objName != operatingPlayerName && targetObj.GetComponent<Team>().teamNum == GameObject.Find(operatingPlayerName).GetComponent<Team>().teamNum)
            {
                //パスの処理
                Debug.Log("パス");
                getScriptPlayer(operatingPlayerName).roopPass(targetObj.transform.position);
                return;
            }
        }
    }

    //=========================================================
    //タッチした対象を判断して行動(タッチされた瞬間だけ呼び出される)
    //=========================================================
    void judgeObjectsAndAct(Vector2 touchPos)
    {
        //プレイヤーの範囲をタッチしたら処理
        TouchAndObjJudge objJudge = GetComponent<TouchAndObjJudge>();
        if (!objJudge.PlayerTouchJudge(touchPos)) return;

        isPlayerTouch = true;
        if (operatingPlayerName != objJudge.objName())
        {
			//////////////////////////////////////////////////////////////////////////////////////条件がダメ?
            if (operatingPlayerName != "" || operatingPlayerName == "" && hitObjName != "")
                isAnotherPlayerTouch = true;
			//////////////////////////////////////////////////////////////////////////////////////

			if (!isAnotherPlayerTouch)
                 setOperationgPlayerName(objJudge.objName());//操作対象を登録。別のプレイヤーがタッチされるまで保存
            else
                hitObjName = objJudge.objName();            //パスかもしれず、操作かもしれないので、保存用変数に名前を保存
        }
        else
        {
            Debug.Log("同じプレイヤー操作");
            //同じプレイヤーを操作していたらリストを削除させ、再度操作開始
            getScriptPlayer(operatingPlayerName).moveColBreak();
        }
        Debug.Log("OperationPlayer = " + operatingPlayerName);
        touchBeginPos = Input.mousePosition;
    }

    //=========================================================
    //リストに追加して、初期位置を更新
    //=========================================================
    void movePosAdd(string opePlayerName, Vector3 addPos)
    {
		Debug.Log("operatingPlayerName = " + opePlayerName);
        getScriptPlayer(opePlayerName).movePosAdd(addPos);
        touchBeginPos = Input.mousePosition;//更新
        //Debug.Log("移動先格納" + addPos);
        //Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), addPos, transform.rotation);//addPosの確認のためCubeを生成するもの
    }

    //=========================================================
    //オブジェクトを指定してプレイヤーのスクリプトを取得する
    //=========================================================
    Player getScriptPlayer(string objName)
    {
		if (support.IsLayerNameToMatch(GameObject.Find(objName), "Player"))
			return GameObject.Find(objName).GetComponent<Player>();
		return null;
    }
    Player getScriptPlayer(GameObject obj)
    {
        return obj.GetComponent<Player>();
    }
    //=========================================================

    //操作するオブジェクト名登録
    void setOperationgPlayerName(string name)
    {
        operatingPlayerName = name;
    }
}