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

public class Ranger : MonoBehaviour
{
    // public GameObject origin;
    float speed = 5;
    Rigidbody2D rb;

    Transform target;
    float range = 20;
    public GameObject bullet;
    float timer = 5;
    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;

        rb.MovePosition(transform.position + (Vector3.left * speed * Time.deltaTime));

        if (timer > 5.0f && target != null && Vector3.Distance(transform.position, target.position) <= range)
        {
            GameObject newBullet = Instantiate(bullet, transform.position, Quaternion.identity);
            newBullet.AddComponent<Rigidbody2D>();
            newBullet.GetComponent<Rigidbody2D>().gravityScale = 0.0f;
            newBullet.GetComponent<Rigidbody2D>().mass = 1.0f;
            newBullet.AddComponent<BulletScript>();
            newBullet.GetComponent<BulletScript>().SetDamage(10);
            newBullet.tag = this.tag;
            newBullet.GetComponent<Rigidbody2D>().AddForce(Vector3.left * 250 * Mathf.Pow(newBullet.GetComponent<Rigidbody2D>().mass, -1.0f) * Time.deltaTime, ForceMode2D.Impulse);
            timer = 0.0f;
        }
    }

    private void OnDestroy()
    {
        //origin.GetComponent<EnemyControl>().enemies.Remove(this.gameObject);
    }

    public void SetTarget(Transform _T)
    {
        target = _T;
    }
    public void SetSpeed(float _S)
    {
        speed = _S;
    }
    public Vector3 GetDirection(Vector3 _A, Vector3 _B)
    {
        Vector3 dist = _A - _B;
        Vector3 dir = new Vector3(0, 0, 0);
        if (dist.x >= dist.y && dist.x >= dist.z)
        {
            dir = new Vector3(dist.x / dist.x, dist.y / dist.x, dist.z / dist.x);
        }
        else if (dist.y >= dist.x && dist.y >= dist.z)
        {
            dir = new Vector3(dist.x / dist.y, dist.y / dist.y, dist.z / dist.y);
        }
        else if (dist.z >= dist.x && dist.z >= dist.y)
        {
            dir = new Vector3(dist.x / dist.z, dist.y / dist.z, dist.z / dist.z);
        }
        return dir;
    }
    private void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == "Player" && col.gameObject.GetComponent<HealthScript>() != null)
        {
            col.gameObject.GetComponent<HealthScript>().TakeDamage(25);
            Destroy(this.gameObject);
        }
    }
}
