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

public class Enemy_Frog : MonoBehaviour
{
    public bool canMove;
    BoxCollider2D PL;
    Rigidbody2D RB;
    Animator Ani;
    public LayerMask G;
    public GameObject Tung;
    GameObject Tunge;
    LineRenderer LR;
    public float wait;
    public Transform ShootPoint;
    private void Start()
    {
        RB = transform.GetComponent<Rigidbody2D>();
        Ani = transform.GetComponent<Animator>();
        LR = transform.GetComponent<LineRenderer>();
        canMove = true;
        wait = -2;
    }
    private void Update()
    {
        if(Tunge != null)
        {
            LR.positionCount = 2;
            LR.SetPosition(0, ShootPoint.position);
            LR.SetPosition(1, Tunge.transform.position);
        }
        else
        {
            LR.positionCount = 0;
        }
        if(wait > 0)
        {
            wait -= Time.deltaTime;
        }
        if (!canMove)
        {
            return;
        }
        if (PL == null)
        {
            FindPlayer();
        }
        else
        {
            GotPlayer();
        }
    }
    private void FindPlayer()
    {
        if(Physics2D.OverlapCircle(transform.position, 100f, G))
        {
            PL = Physics2D.OverlapCircle(transform.position, 100f, G).transform.GetComponent<BoxCollider2D>();
        }
    }
    private void GotPlayer()
    {
        if (!Physics2D.OverlapCircle(transform.position, 100f, G))
        {
            PL = null;
            return;
        }
        if (Vector2.Distance(transform.position, PL.bounds.center) >= 60f)
        {
            JumpToPlayer();
            return;
        }
        if(wait < 0 && wait != -1)
        {
            Attack();
            wait = -1;
        }
    }
    private void Attack()
    {
        Ani.Play("Frog_Shoot");
        canMove = false;
    }
    private void JumpToPlayer()
    {
        if((PL.bounds.center - transform.position).normalized.x > 0)
        {
            transform.rotation = new Quaternion(0, 180, 0, 0);
        }
        else
        {
            transform.rotation = new Quaternion(0, 0, 0, 0);
        }
        RB.AddForce(new Vector2((PL.bounds.center - transform.position).normalized.x * 10, 30), ForceMode2D.Impulse);
        Ani.Play("Frog_Run");
        canMove = false;
    }
    public void shoot()
    {
        Tunge = GameObject.Instantiate(Tung, ShootPoint.position, Quaternion.AngleAxis((Mathf.Atan2((ShootPoint.position.y - PL.bounds.center.y), (ShootPoint.position.x - PL.bounds.center.x)) * Mathf.Rad2Deg) + 180, Vector3.forward));
        Tunge.GetComponent<Frog_Tung>().setDmg = 5;
        Tunge.GetComponent<Frog_Tung>().OwnTag = transform.tag;
    }
}