using System;
using UnityEngine;
public class AttackShip2 : MonoBehaviour {

    public float speed = 1;
    private Transform target;
    // Use this for initialization
    void Start () {
        GameObject[] ships = GameObject.FindGameObjectsWithTag("Enemy");
        if(ships.Length == 0)
        {
            return;
        }
        GameObject nearest = FindNearest(ships);
        target = nearest.transform;
    }
    private GameObject FindNearest(GameObject[] targets)
    {
        GameObject nearest = targets[0];
        float minDistance = Vector2.Distance(transform.position, nearest.transform.position);
        for (int i = 1; i < targets.Length; i++)
        {
            float currentDistance = Vector2.Distance(transform.position, targets[i].transform.position);
            if (currentDistance < minDistance)
            {
                nearest = targets[i];
                minDistance = currentDistance;
            }
        }
        return nearest;
    }
    // Update is called once per frame
    void Update () {

        float step = speed * Time.deltaTime;
        if (target == null)
        {
            FindNewEnimie();
            if(target == null)
            {
                //transform.position = Vector3.MoveTowards(transform.position, new Vector3(transform.position.x, transform.position.y + 100), step);
                return;
            }
        }
        Debug.Log("Following the enemie" + target.position.x + " " + target.position.y);
        //int rotationOffset = 90;
        //Vector2 targetDir = target.position - transform.position;
        //Vector2 difference = targetDir;
        //targetDir.Normalize();
        //float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        //transform.rotation = Quaternion.Euler(0f, 0f, rotZ + rotationOffset);
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }

    private void FindNewEnimie()
    {
        GameObject[] ships = GameObject.FindGameObjectsWithTag("Enemy");
        if (ships.Length == 0)
        {
            return;
        }
        GameObject nearest = FindNearest(ships);
        target = nearest.transform;
    }
}
