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

public class OrbitBody : MonoBehaviour {
	public float rotateSpeed;
	float distance;
	public Transform targetBody;
	Vector3 lastPosition;

	public GameObject helpText;

	float pushForce;
	Vector3 pushDirection;

	// Use this for initialization
	void Start () {
		pushForce = 0f;
		pushDirection = Vector3.zero;
	}


	void Update(){
		if(GlobalScript.orbiting){
			pushForce = 0f;
			pushDirection = Vector3.zero;
			if(Input.GetButton("Detatch")){
				Detatch();
			}
		}
		if(pushForce > 0f){
			transform.position += pushDirection * Time.deltaTime * 10f;
			pushForce -= Time.deltaTime;
		}
	}

	void LateUpdate () {
		if(!GlobalScript.orbiting)
			return;
		Vector3 deltaPosition = targetBody.position - lastPosition;
		lastPosition = targetBody.position;
		transform.position += deltaPosition;
		//angle -= (speed * Time.deltaTime) * (distance / 1000f);
		//Vector3 newPos = new Vector3(Mathf.Sin(angle) * -distance, 0f, Mathf.Cos(angle) * -distance);
		transform.RotateAround(targetBody.position, Vector3.up, -Input.GetAxis("Mouse X") * Time.deltaTime * rotateSpeed);
	}

	public void StartOrbit(Transform t){
		GlobalScript.orbiting = true;
		targetBody = t;
		distance = (transform.position - targetBody.position).magnitude;
		lastPosition = targetBody.position;
		if(distance - targetBody.localScale.x < 1f){
			distance = targetBody.localScale.x + 1f;
		}
		transform.position = targetBody.position + ((transform.position - targetBody.position).normalized * distance);

		transform.LookAt(targetBody);

		helpText.SetActive(true);

		t.gameObject.SendMessage("StartConversation");

	}

	public void Detatch(){
		OrbitScript other = targetBody.GetComponent<OrbitScript>();
		GlobalScript.orbiting = false;
		GlobalScript.attachDelay = 2f;

		helpText.SetActive(false);

		float force = 1f;
		//Debug.Log(force);

		if(pushForce < 0f){
			pushDirection = Vector3.zero;
			pushForce = 0f;
		}

		pushDirection = (transform.position - other.transform.position).normalized;
		pushForce = force;
	}

}
