using UnityEngine;

public class Gun : MonoBehaviour
{
    public Bullet bullet1Prefab;
    public Bullet bullet2Prefab;
    public bool staticInstance;
    public Transform up;
    public Transform anchor;
    public Transform point;
    public bool holdToFire;
    public bool rotateToLock;
    public float rotateSmooth = 10;
    public float minLockDistance = 2;
    public float randomDirection = 5;
    public float cooldown = 0.1f;

    private float nextShootTime;

    public GameManager game => GameManager.instance;

    private void Start()
    {

    }

    private void Update()
    {
        if (rotateToLock)
        {
            var targetRotation = anchor.parent.rotation;
            if (Physics.Raycast(Camera.main.ViewportPointToRay(Vector2.one * 0.5f), out var hit, 1000) && hit.distance > minLockDistance)
            {
                targetRotation = Quaternion.LookRotation(hit.point - anchor.position, up.up);
            }
            anchor.rotation = Quaternion.Lerp(anchor.rotation, targetRotation, rotateSmooth * Time.deltaTime);
        }

        if (!staticInstance)
        {
            if (GetMouse(0))
            {
                Fire(bullet1Prefab);
            }
            else if (GetMouse(1))
            {
                Fire(bullet2Prefab ?? bullet1Prefab);
            }
        }
        else
        {
            var item = GetMouse(0) ? bullet1Prefab : GetMouse(1) ? bullet2Prefab : null;
            if (item != null)
            {
                item.gameObject.SetActive(true);
                bullet1Prefab.gameObject.SetActive(bullet1Prefab == item);
                bullet2Prefab.gameObject.SetActive(bullet2Prefab == item);
            }
            else
            {
                bullet1Prefab.gameObject.SetActive(false);
                bullet2Prefab.gameObject.SetActive(false);
            }
        }
    }

    public bool GetMouse(int button)
    {
        if (holdToFire)
            return Input.GetMouseButton(button);
        else
            return Input.GetMouseButtonDown(button);
    }

    public void Fire(Bullet bulletPrefab)
    {
        if (Time.timeScale == 0)
            return;

        // if (bulletPrefab is BubbleContainer)
        // {
        //     if (game.level.)
        // }

        if (Time.time > nextShootTime)
        {
            nextShootTime = Time.time + cooldown;
            var bubble = Instantiate(bulletPrefab, point.position, point.rotation);
            bubble.transform.Rotate(new Vector3(Random.Range(-randomDirection, randomDirection), Random.Range(-randomDirection, randomDirection)));
        }
    }
}