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

public class OrbitScript : MonoBehaviour {
	public float distance;
	public float speed;
	public float rotateSpeed;
	public float angle = 0;
	Vector3 obliqueAxis;


	// Use this for initialization
	void Start () {
		if(distance == 0){
			distance = transform.position.magnitude;
			speed = Random.Range(1f, 6.5f);
			rotateSpeed = Random.Range(-500f, 500f);
			angle = Mathf.Atan2(transform.position.z, transform.position.x);
			angle = angle * (180f / Mathf.PI);
		}
		distance = Mathf.Abs(distance);
		if(angle == 0){
			angle = Mathf.Atan2(transform.position.z, transform.position.x);
			angle = angle * (180f / Mathf.PI);
		}
		if(transform.position.y > 1f){
			obliqueAxis = Vector3.Cross(transform.position, Vector3.right);
		}else{
			transform.position = new Vector3(Mathf.Sin(angle) * distance, transform.position.y, Mathf.Cos(angle) * distance);
		}
	}
	
	// Update is called once per frame
	void Update () {
		if(!GlobalScript.planetaryMovementEnabled)
			return;
		transform.Rotate(0f, -rotateSpeed * Time.deltaTime, 0f);
		//angle -= (speed * Time.deltaTime) * (distance / 1000f);
		//Vector3 newPos = new Vector3(Mathf.Sin(angle) * -distance, 0f, Mathf.Cos(angle) * -distance);
		if(transform.position.y > 1f){
			transform.RotateAround(Vector3.zero, obliqueAxis, -speed * Time.deltaTime * (66f / distance));
		}else{
			transform.RotateAround(Vector3.zero, Vector3.up, -speed * Time.deltaTime * (66f / distance));
		}
		if(GlobalScript.orbiting)
			return;
		Collider[] col = Physics.OverlapSphere(transform.position, transform.localScale.x, 1 << LayerMask.NameToLayer("Player"));
		if(col.Length > 0)
			col[0].gameObject.SendMessage("Collide", this, SendMessageOptions.DontRequireReceiver);

		//transform.position = newPos;

	}
}
