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

namespace Destructible2D
{
	public class controller2 : MonoBehaviour
	{
		private float movementSpeed = 5f;
		public GameObject ExplosionPrefab;
		public int FractureCount = 1;
		public float speed;
		private Transform target;
		// Use this for initialization
		void Start()
		{
			GameObject[] targets = GameObject.FindGameObjectsWithTag("Turret");
			GameObject nearest = FindNearest(targets);
			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()
		{
			//GetComponent<Rigidbody2D>().MovePosition(GetComponent<Rigidbody2D>().position+Vector2.forward * movementSpeed * Time.deltaTime);
			GetComponent<Rigidbody2D>().AddForce(transform.up * movementSpeed * Time.deltaTime);
			float step = speed * Time.deltaTime;
			int rotationOffset = 180;
			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);

		}

		void OnCollisionEnter2D(Collision2D coll)
		{
			if (coll.gameObject.tag == "Planet" || coll.gameObject.tag == "Turret" || coll.gameObject.tag == "Asteroid")
			{

				//Debug.Log (coll.gameObject.name);
				var screenPoint = GetComponent<Transform>().position;
				var screenRotation = GetComponent<Transform>().rotation;
				//var worldPoint    = Camera.main.ScreenToWorldPoint(screenPoint);
				//var collider      = Physics2D.OverlapPoint(worldPoint);




				var destructible = coll.gameObject.GetComponent<D2dDestructible>();


				Destroy(this.gameObject);
				if (ExplosionPrefab != null)
				{
					//var worldRotation = Quaternion.Euler(0.0f, 0.0f, Random.Range(0.0f, 360.0f)); // Random rotation around Z axis

					Instantiate(ExplosionPrefab, screenPoint, screenRotation);
				}







			}
		}


	}
}
