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

public class CannonController : MonoBehaviour
{
    public GameObject cannonBallPrefab;
    public Transform cannonHole;
    public Animator animator;
    public Animator cannonExplosion;
    public float cannonForceMagnitude;
    public float orientationSpeed;
    public float fireRate;
    private float firePeriod;

    private Vector3 mousePosition = new Vector3();
    private float lastFireTime;
    public bool CanFire
    {
        get
        {
            return Time.time - lastFireTime > firePeriod;
        }
    }


    void Start()
    {
        firePeriod = 1 / fireRate;
    }

    public void Fire()
    {
        //var cannonBall = Instantiate(cannonBallPrefab, cannonHole.position, Quaternion.identity);
        var cannonBall = CannonBallPoolManager.Instance.GetCannonBall();
        cannonBall.transform.position = cannonHole.position;

        var orientation = (transform.localRotation.eulerAngles.z + 90) * Mathf.Deg2Rad;

        Vector2 cannonForce = new Vector2(cannonForceMagnitude * Mathf.Cos(orientation), cannonForceMagnitude * Mathf.Sin(orientation));

        cannonBall.GetComponent<Rigidbody2D>().AddForce(cannonForce);

        animator.ResetTrigger("Idle");
        animator.ResetTrigger("Fire");
        animator.SetTrigger("Fire");

        cannonExplosion.gameObject.transform.position = this.cannonHole.position;
        cannonExplosion.gameObject.transform.rotation = this.transform.rotation;

        cannonExplosion.ResetTrigger("Idle");
        cannonExplosion.ResetTrigger("Explode");
        cannonExplosion.SetTrigger("Explode");

        AudioManager.Instance.PlayCannon();

        lastFireTime = Time.time;
    }

    public void Orient()
    {
        //float orientation = NormalizeAngle(transform.localRotation.eulerAngles.z) + Input.GetAxis("Vertical") * -1f * orientationSpeed;
        //orientation = Mathf.Clamp(orientation, -60f, 60f);
        //transform.localRotation = Quaternion.Euler(transform.localRotation.x, transform.localRotation.y, orientation);

        mousePosition.Set(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z - transform.position.z);
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
        mousePosition.z = transform.position.z;
        float angle = Mathf.Atan2(mousePosition.y - transform.position.y, mousePosition.x - transform.position.x) * Mathf.Rad2Deg;
        angle -= 90;
        transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, angle);
    }

    // Normalize angle to a value between -180 and 180
    private float NormalizeAngle(float angle)
    {
        if (angle > 180)
        {
            angle -= 360;
        }

        return angle;
    }
}
