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

////////
//得点後2フレームごとに0に戻されてしまうバグがあるため要検討
////////

//チームごとの得点を計算して表示する
public class Score : MonoBehaviour
{
    GameManager gmanager;
    FlagManager flag;

    public bool draw = false;
    //スコアを表示するGUI格納用
    [SerializeField] GameObject scoreText1;
    [SerializeField] GameObject scoreText2;


    int[] spoint = new int[2];     //各チームのスコア 

    public float scorePointDistance = 24f; //2点、3点の判定距離

    //ゴールポストオブジェクト格納用
    GameObject[] goalPost = new GameObject[2];

    //ボールを持っているキャラクター
    public GameObject BallChar = null;

    public bool win = false;

    void Start()
    {
        flag = GameObject.Find("Manager").GetComponent<FlagManager>();
        gmanager = GameObject.Find("Manager").GetComponent<GameManager>();

        scoreText1 = GameObject.Find("Score_1");
        scoreText2 = GameObject.Find("Score_2");
        goalPost[0] = GameObject.Find("Goal Post0");
        goalPost[1] = GameObject.Find("Goal Post1");

        spoint[0] = 0;
        spoint[1] = 0;
        displayScore(scoreText1, spoint[0]);
        displayScore(scoreText2, spoint[1]);
    }

    void Update()
    {
        //Debug.Log("score2 = " + score2);
        if (spoint[0] > spoint[1] && !win)
        {
            win = true;
            draw = false;
        }
        else if (spoint[0] < spoint[1])
        {
            win = false;
            draw = false;
        }
        else if (spoint[0] == spoint[1])
        {
            win = false;
            draw = true;

        }
    }
    //各チームのスコア加算==============================
    public void S1add()
    {
        //if(flag.)
        spoint[0] += IsTwoOrThreePoint(goalPost[0]);
        //Debug.Log("score1ゴール");
        Physics.gravity = new Vector3(0, -15, 0);
        displayScore(scoreText1, 0);
        flag.fieldGoal = true;
        gmanager.SetChara(1);
    }
    public void S2add()
    {
        spoint[1] += IsTwoOrThreePoint(goalPost[1]);
        //Debug.Log("score2ゴール" + score2);
        Physics.gravity = new Vector3(0, -15, 0);
        displayScore(scoreText2, 1);
        flag.fieldGoal = true;
        gmanager.SetChara(0);
    }
    //================================================

    //ゴールとプレイヤーの距離から2ポイント・3ポイントを判定
    int IsTwoOrThreePoint(GameObject gp)
    {
        Vector3 g_playerPos = BallChar.transform.position;
        Vector3 goalPos = gp.transform.FindChild("GoalTargetPoint").transform.position;
        g_playerPos.y = goalPos.y;
        //3ポイント地点よりゴールに近い
        if (Vector3.Distance(goalPos, g_playerPos) <= scorePointDistance)
            return 2;
        return 3;
    }

    //プレイ画面にスコアをテキストとして表示する 
    public void displayScore(GameObject stex, int team)
    {
        //stexのtextにscore[team]点を書き込む
        stex.GetComponent<Text>().text = (spoint[team]).ToString();
    }

}