using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour {

	public VulnerableScript vul;
	public bool isStable;
	public GameObject startPlanet;

	public float distance;
	public float timeMultiplier;
	public float orbitMultiplier;

	public GameObject spriteObject;
	public float rotationSpeed;

	public static PlayerScript player;

	// Use this for initialization
	void Start () {
		//vul.enabled = false;
		player = this;
	}
	
	// Update is called once per frame
	void Update () {
		if (isStable) {
			this.transform.localPosition = new Vector3 (Mathf.Cos (Time.timeSinceLevelLoad * timeMultiplier) * distance, Mathf.Sin (Time.timeSinceLevelLoad * timeMultiplier) * distance, 0);
		} else {
			if (Camera.main.WorldToViewportPoint (transform.position).x > 1 || Camera.main.WorldToViewportPoint (transform.position).x < 0 ||
			    Camera.main.WorldToViewportPoint (transform.position).y > 1 || Camera.main.WorldToViewportPoint (transform.position).y < 0) {
				StageManagerScript.instance.StartReloadingThisStage ();
			}
		}

		spriteObject.transform.Rotate (Vector3.forward, rotationSpeed * Time.deltaTime);
	}

	void FixedUpdate(){
		if (!isStable) {
			this.vul.GravityUpdate ();
		}
	}

	public void ExitOrbit(){
		this.isStable = false;
		Vector3 firstImpulse = new Vector3 (Mathf.Cos (Time.timeSinceLevelLoad * timeMultiplier), Mathf.Sin (Time.timeSinceLevelLoad * timeMultiplier));
		firstImpulse = Quaternion.AngleAxis (90, Vector3.forward) * firstImpulse * orbitMultiplier; 
		this.vul.SetFirstImpulse (firstImpulse);
		this.transform.parent = null;
	}

	void OnTriggerEnter2D(Collider2D other){
		if (other.tag.Equals("Target")){
			EndPlanetScript target = other.GetComponent<EndPlanetScript> ();
			if (target) {
				target.DestroyMe ();
			}
			StageManagerScript.instance.StartLoadingNextStage ();
			Destroy (this.gameObject);
		}

		if (other.tag.Equals ("Obstacle")) {
			StageManagerScript.instance.StartReloadingThisStage ();
			Destroy (this.gameObject);
		}
	}
}
