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

public class CharController : MonoBehaviour {
	public GameObject spaceShipInternals;
	private Rigidbody2D rigidbody2d;
	private List<GameObject> closeControllers = new List<GameObject>();

	// Use this for initialization
	void Start () {
		rigidbody2d = GetComponent<Rigidbody2D>();
	}
	
	// Update is called once per frame
	void Update () {
		GameController.mainCamera.transform.position = new Vector3(transform.position.x, transform.position.y, GameController.mainCamera.transform.position.z);
		GameController.mainCamera.transform.rotation = spaceShipInternals.transform.rotation;

		//Friction
		rigidbody2d.velocity = Vector2.zero;

		Vector2 speedGain = new Vector2(Input.GetAxis("Horizontal") * 5, Input.GetAxis("Vertical") * 5);
		if (speedGain.magnitude > Mathf.Epsilon) {
			rigidbody2d.velocity += speedGain.Rotate(spaceShipInternals.transform.rotation.eulerAngles.z);
			transform.localRotation = Quaternion.AngleAxis(speedGain.ToAngle(), Vector3.forward);
		}

		if (Input.GetKeyDown("space")) {
			GameController.instantiate(TemplateManager.getEVA(0), transform.position, transform.rotation.eulerAngles.z,
				spaceShipInternals.transform.parent.FindChild("Collider").GetComponent<Rigidbody2D>().velocity);
			Destroy(gameObject);
		}

		if (Input.GetKeyDown("e") && closeControllers.Count > 0) {
			this.enabled = false;
			closeControllers[0].transform.parent.gameObject.GetComponent<ModuleController>().setCharController(this);
			closeControllers[0].transform.parent.gameObject.GetComponent<ModuleController>().enabled = true;
		}
	}

	void OnTriggerEnter2D(Collider2D collider) {
		if (collider.gameObject.layer == 14) { // Zone
			closeControllers.Add(collider.gameObject);
		}
	}

	void OnTriggerExit2D(Collider2D collider) {
		if (collider.gameObject.layer == 14) { // Zone
			closeControllers.Remove(collider.gameObject);
		}
	}
}