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

public class Weapon : MonoBehaviour
{
	public GameObject bulletPrefab;
	public GameObject shooter;

	public GameObject explosionEffect;
	public LineRenderer lineRenderer;

	private Transform _firePoint;



	void Awake()
	{
		_firePoint = transform.Find("FirePoint");
	}

	// Start is called before the first frame update
	void Start()
    {
		//Invoke("Shoot", 1f);
		//Invoke("Shoot", 2f);
		//Invoke("Shoot", 3f);
	}

    // Update is called once per frame
    void Update()
    {
        
    }

	public void Shoot()
	{
		if (bulletPrefab != null && _firePoint != null && shooter != null) {
			GameObject myBullet = Instantiate(bulletPrefab, _firePoint.position, Quaternion.identity) as GameObject;

			Bullet bulletComponent = myBullet.GetComponent<Bullet>();

			if (shooter.transform.localScale.x < 0f) {
				// Left
				bulletComponent.direction = Vector2.left; // new Vector2(-1f, 0f)
			} else {
				// Right
				bulletComponent.direction = Vector2.right; // new Vector2(1f, 0f)
			}
		}
	}

	public IEnumerator ShootWithRaycast()
	{
		if (explosionEffect != null & lineRenderer != null) {

			RaycastHit2D hitInfo = Physics2D.Raycast(_firePoint.position, _firePoint.right);

			if (hitInfo) {
				Transform player = hitInfo.transform;

				// Can do whatever you want with the player
				// player.ApplyDamage(5);

				// Instantiate explosion on hit point
				Instantiate(explosionEffect, hitInfo.point, Quaternion.identity);

				// Set line renderer from our firePoint to the hit point
				lineRenderer.SetPosition(0, _firePoint.position);
				lineRenderer.SetPosition(1, hitInfo.point);
			} else {

				// If no point, set line renderer like too long
				lineRenderer.SetPosition(0, _firePoint.position);
				lineRenderer.SetPosition(1, _firePoint.position + _firePoint.right * 100);
			}

			// Enable and disable lineRenderer for a moment so it is visible
			lineRenderer.enabled = true;

			yield return 0;

			lineRenderer.enabled = false;

		}
	}
}
