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

public class CannonControls : MonoBehaviour
{
    [SerializeField] private GameObject projectile = null;
    [SerializeField] private float shootingDelay = 0.2f;
    [SerializeField] private Collider[] cannonColliders = null;
    private float delay;
    private float timeLeftToShoot = 0f; // the amount of time passed since last shot
    private bool isOn = true;

    void Start()
    {
        delay = shootingDelay;
        GameEvents.instance.onNextLevelEvent += PauseControl;
        GameEvents.instance.onGameLostEvent += TurnOffControls;
        GameEvents.instance.onGameRestartEvent += TurnOnControls;
        GameEvents.instance.onGameLostEvent += TurnOffColliderTrigger;
        GameEvents.instance.onGameRestartEvent += TurnOnColliderTrigger;
    }

    void Update()
    {
        if(isOn && Input.GetKey(KeyCode.Mouse0))
        {
            if (timeLeftToShoot <= 0f)
            {
                // start shooting cannonballs
                GameObject childObject = Instantiate(projectile) as GameObject;
                //foreach (Collider collider in cannonColliders)
                //    Physics.IgnoreCollision(childObject.GetComponent<Collider>(), collider, true);
                childObject.transform.parent = gameObject.transform;
                childObject.transform.localPosition = new Vector3(0, 0, 0);
                childObject.transform.LookAt(GameObject.Find("Shooting Target").transform);
                if(delay > (shootingDelay * 1f) / 2f)
                    delay *= 0.95f;
                timeLeftToShoot = delay;
            }
            else
            {
                timeLeftToShoot -= Time.deltaTime;
            }
        }
        if (Input.GetKeyUp(KeyCode.Mouse0))
        {
            delay = shootingDelay;
            timeLeftToShoot = 0f;
        }
    }

    public void TurnOnControls()
    {
        isOn = true;
    }

    public void TurnOffControls()
    {
        isOn = false;
    }

    private void TurnOnColliderTrigger()
    {
        foreach (Collider collider in cannonColliders)
            collider.isTrigger = true;
    }

    private void TurnOffColliderTrigger()
    {
        foreach (Collider collider in cannonColliders)
            collider.isTrigger = false;
    }

    void PauseControl()
    {
        StartCoroutine("StopControls");
    }

    IEnumerator StopControls()
    {
        isOn = false;
        delay = shootingDelay;
        yield return new WaitForSeconds(1);
        isOn = true;
    }
}
