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

public class GameController : MonoBehaviour {
	public GameObject mainCameraNonStatic;
	public static GameObject mainCamera;
	public Transform templates;

	public static List<GameObject> largeSpaceShips = new List<GameObject>();
	public static Dictionary<int, GameObject> sharedGameObjects = new Dictionary<int, GameObject>();
	public static List<GameObject> listSharedGameObjects = new List<GameObject>();

	public static Dictionary<int, Player> players = new Dictionary<int, Player>();
	public static Player player = null;

	public static float timeChangedEVA = 0.0f;

	void Awake () {
		initStaticVar();
		TemplateManager.init(templates);
	}

	void Update () {
		
	}

	private void initStaticVar() {
		mainCamera = mainCameraNonStatic;
	}

	public static GameObject instantiate(int id, GameObject original, Vector2 position, float rotation = 0.0f, Vector2 velocity = new Vector2()) {
		GameObject clone = Instantiate(original, new Vector3(position.x, position.y), Quaternion.identity);
		clone.transform.Rotate(0, 0, rotation);
		if (velocity.magnitude > 0) {
			clone.GetComponent<Rigidbody2D>().velocity = velocity;
		}
		SharedGameObject shared = clone.GetComponent<SharedGameObject>();
		shared.GetComponent<SharedGameObject>().id = id;

		if (clone.GetComponent<CharController>() != null) {
			clone.transform.position = new Vector3(position.x, position.y, - 1);
		}

		if (clone.GetComponent<SharedGameObject>().type == ObjectType.LargeSpaceShip) {
			clone.transform.position = Vector3.zero;
			clone.transform.rotation = Quaternion.identity;

			clone.transform.GetChild(0).position = new Vector3(position.x, position.y);
			clone.transform.GetChild(0).rotation = Quaternion.identity;
			clone.transform.GetChild(0).Rotate(0, 0, rotation);
		}

		clone.GetComponentsInChildren(true, shared.internalControllers);
		for (int i = 0; i < shared.internalControllers.Count; i++) {
			shared.internalControllers[i].internalID = i;
			shared.internalControllers[i].init();
		}

		return clone;
	}

	public static void destroy(GameObject obj) {
		Destroy(obj);
	}

	public static void registerNewSharedGameObject(GameObject obj) {
		int id = obj.GetComponent<SharedGameObject>().id;

		Debug.Assert(!sharedGameObjects.ContainsKey(id));
		sharedGameObjects[id] = obj;

		Debug.Assert(listSharedGameObjects.Count == id);
		listSharedGameObjects.Add(obj);
	}

	public static void updateNewSharedGameObject(GameObject obj) {
		int id = obj.GetComponent<SharedGameObject>().id;

		Destroy(sharedGameObjects[id]);

		sharedGameObjects[id] = obj;
		listSharedGameObjects[id] = obj;
	}

	public static void initGame() {
		Requests.spawn(ObjectType.LargeSpaceShip, 0, Vector2.zero, 0);
		int characterID = Requests.spawn(ObjectType.Character, 0, Vector2.zero, 0, 0);
		Requests.newPlayer(characterID, -1);
	}
}
