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

public class BasicEnemy : MonoBehaviour {

    public Transform bulletPivot;
    public int health;
    public int damage;
    public float speed;
    public float maxUpwards;
    public GameObject bullet;
    public GameObject explosion;
    public AudioClip clip;

    public float maxCooldown;
    
    private float currentCooldown;
    private Rigidbody rb;
    private float y;
	// Use this for initialization
	void Start ()
    {
        rb = this.GetComponent<Rigidbody>();	
	}
	
	// Update is called once per frame
	void Update ()
    {
	    if(currentCooldown<=0)
        {
            Shoot();
            currentCooldown = maxCooldown;
        }
        else
        {
            currentCooldown -= Time.deltaTime;
        }
	}
    void FixedUpdate()
    {
        y = Mathf.PingPong(Time.time*4, maxUpwards*2);
        rb.velocity = new Vector3(speed, y-maxUpwards, 0);
    }
    public void TakeDamage(int a)
    {
        health -= a;
        if(health<=0)
        {
            AudioSource.PlayClipAtPoint(clip, this.transform.position);
            GameObject exp = Instantiate(explosion, this.transform.position, this.transform.rotation, null);
            Destroy(exp, 0.25f);
            Destroy(this.gameObject);
        }
    }

    public void Shoot()
    {
        GameObject newBullet = Instantiate(bullet, bulletPivot.position, Quaternion.Euler(0,0,0), null);
    }
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.collider.tag=="Player")
        {
            //Explode this thing
            collision.gameObject.GetComponent<PlayerHealth>().ModifyHealth(-damage);
            GameObject exp = Instantiate(explosion, this.transform.position, this.transform.rotation, null);
            Destroy(exp, 0.25f);
            Destroy(this.gameObject);
        }
    }
}
