using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;


public class BallFallScript : MonoBehaviour
{
    [SerializeField]
    private GameObject Balls;

    private bool isTrigger = false;

    private GameObject ball;

    private float TimeCount = 0f;
    public float maxTimeCount = 1f;

    public int NextBall = 0;

    private bool isfall = false;

    private GameObject Gamemanager;
    // Start is called before the first frame update
    void Start()
    {
        ball = Instantiate(Balls,this.transform);
        ball.GetComponent<BallScripts>().nowBall = Random.Range(1,6);
        NextBall = Random.Range(1, 6);
        Gamemanager = GameObject.Find("GameManager");
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.position = new Vector3(ScreenPointToWorldPoint(Input.mousePosition, Camera.main).x, 3f, 0f);
        if (this.transform.position.x >= 3f)
        {
            this.transform.position = new Vector3(3f, 3f, 0f);
;       }
        if (this.transform.position.x <= -3f)
        {
            this.transform.position = new Vector3(-3f, 3f, 0f);
        }

        if (!isTrigger)
        {
            if (Input.GetMouseButtonDown(0))
            {
                isTrigger = true;
            }
        }
        else
        {
            if (isfall == false)
            {
                ball.AddComponent<CircleCollider2D>();
                ball.GetComponent<CircleCollider2D>().radius = 0.5f;
                ball.AddComponent<Rigidbody2D>();
                ball.GetComponent<BallScripts>().isfall = true;
                ball.transform.parent = null;
                isfall = true;
            }
            TimeCount += Time.deltaTime;
        }

        if(TimeCount >= maxTimeCount && Gamemanager.GetComponent<GameManager>().isGameOver == false)
        {
            isfall = false;
            TimeCount = 0;
            isTrigger = false;
            ball = Instantiate(Balls, this.transform);
            ball.GetComponent<BallScripts>().nowBall = NextBall;
            NextBall = Random.Range(1, 6);
        }
    }

    


    //XN[W[hWɕϊ
    public static Vector3 ScreenPointToWorldPoint(Vector3 targetPos, Camera targetCamera)
    {
        return targetCamera.ScreenToWorldPoint(targetPos);
    }

}
