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

public class IncomingWave : MonoBehaviour {

	public float Speed = 1F;
	private Rigidbody rigid;
	// Use this for initialization

	public float KippSpeed = 2F;
	private float kippTimer = 0;
	
	private Vector3 kippStartPos;
	private Vector3 kippEndPos;
	private float diff;

	private Transform ship;
	void SetKippPos(Transform other) {
		kippStartPos = other.rotation.eulerAngles;
		
		Vector3 dirToTarg = other.position-transform.position;

		float angle = Vector3.Angle(transform.forward,dirToTarg);
		
		
		//Debug.Log("Angle is: "+angle);


		if(angle > 0) {
			kippEndPos = new Vector3(0,0,-110);
		} else {
			kippEndPos = new Vector3(0,0,110);
		}
	}
	void Awake () {
		rigid = GetComponent<Rigidbody>();
		
	}
	
	// Update is called once per frame
	void Update () {
		rigid.AddForce(rigid.transform.forward*Speed,ForceMode.Force);
	}

	void OnTriggerEnter(Collider other) {
		if(other.GetComponent<PlayerShipController>() != null) {
			ship = other.GetComponent<ShipController>().Ship.transform;
			diff = getDirDifference(ship.forward);
			SetKippPos(ship);
		}
	}

	void OnTriggerExit(Collider other) {
		if(other.GetComponent<PlayerShipController>() != null) {
			other.GetComponent<PlayerShipController>().PropUp();
			Destroy(this.gameObject,10);
		}
		
	}


	void OnTriggerStay(Collider other)
	{
		if(other.GetComponent<PlayerShipController>() != null) {
			
			kippTimer+= Time.deltaTime*KippSpeed;
			Vector3 currRot = ship.localRotation.eulerAngles;			
			
			kippStartPos.y = currRot.y;
			kippStartPos.x = currRot.x;
			kippEndPos.y = currRot.y;
			kippEndPos.x = currRot.x;
			
			kippEndPos.z*=diff;
			Vector3 newRot = Vector3.Lerp(kippStartPos,kippEndPos,kippTimer);
			ship.localRotation = Quaternion.Lerp(Quaternion.Euler(kippStartPos),Quaternion.Euler(kippEndPos),kippTimer);
			//ship.transform.localRotation = Quaternion.Euler(newRot);

			Rigidbody r = other.GetComponent<Rigidbody>();
			r.velocity *= 1.02F-diff;


			
		}
		//ship.transform.localRotation = kippEndPos;
	}


	float getDirDifference(Vector3 otherDir) {

		Vector3 inverseShipDir = otherDir;
		inverseShipDir.y = 0;
		float dif = Vector3.Angle(inverseShipDir,transform.forward);
		
		dif = Mathf.Abs(dif);
		dif = Mathf.Clamp(dif,0,90);
		//float diff = Vector3.Angle(transform.forward*-1,otherDir);
		float res = Mathf.InverseLerp(0,90,dif);
		Debug.Log("RS: "+res);
		if(res > 0.25) {
			res = 1;
			PlayerShipController.instance.TakeDamage(1);
		} else {
			WaveManager.instance.AddScore(1);
			res = 0;
		}
		return res;

	}
}
