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

public class CharController : Controller {
	public int largeSpaceShipID;
	public GameObject spaceShipInternals;
	private Rigidbody2D rigidbody2d;
	private List<GameObject> closeControllers = new List<GameObject>();
	Vector2 oldVelocity = Vector2.zero;

	// 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") * 5f, Input.GetAxis("Vertical") * 5f);
		if (speedGain.magnitude > Mathf.Epsilon) {
			rigidbody2d.velocity += speedGain.Rotate(spaceShipInternals.transform.rotation.eulerAngles.z);
			transform.localRotation = Quaternion.AngleAxis(speedGain.ToAngle(), Vector3.forward);
		}
		if (rigidbody2d.velocity != oldVelocity) {
			Requests.move(gameObject);
			oldVelocity = rigidbody2d.velocity;
		}

		if (Input.GetKeyDown("space")) {
			Requests.EVA(gameObject.GetComponent<SharedGameObject>().id);
		}

		if (Input.GetKeyDown("e") && closeControllers.Count > 0) {
			Debug.Log(closeControllers[0]);
			SharedGameObject spaceship = closeControllers[0].transform.parent.GetComponent<ModuleController>().spaceShip.GetComponent<SharedGameObject>();
			Requests.changeController(spaceship.id, spaceship.internalControllers[0].internalID);
		}
	}

	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);
		}
	}
}