using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using UnityEngine;
using System;

public class IlluminatorModule : AngularModule {
	private int slots;

	public IlluminatorModule(JObject json) : base(json) {
		slots = (int)json["slots"];

		icon = Resources.Load("Sprites/Modules/Icons/Illuminators/" + getUniqueName(), typeof(Sprite)) as Sprite;
		silhouette = Resources.Load("Sprites/Modules/Silhouettes/Illuminators/" + getUniqueName(), typeof(Sprite)) as Sprite;
	}

	public int getSlots() {
		return slots;
	}

	public static IlluminatorModule[] loadModules(string[] filenames) {
		Array.Sort(filenames);
		IlluminatorModule[] array = new IlluminatorModule[filenames.Length];

		for (int i = 0; i < filenames.Length; i++) {
			array[i] = new IlluminatorModule(jsonFromFile(filenames[i]));
		}

		return array;
	}

	override public void updateClasses() {
	}

	override public ModuleData getData(int parent, float angleOffset, Vector position) {
		return new IlluminatorModuleData(parent, this, angleOffset, position);
	}
}

public class IlluminatorModuleData : AngularModuleData { //TODO : remove illuminated if module is kaput
	Set<DeployedUnit> currentlyTargeted;

	public IlluminatorModuleData(int parent, Module template, float angleOffset, Vector position) : base(parent, template, angleOffset, position) {
		currentlyTargeted = new Set<DeployedUnit>();
	}

	public int getRemainingSlots() {
		return ((IlluminatorModule)template).getSlots() - currentlyTargeted.count();
	}

	public void addTargetedMissile(DeployedUnit missile) {
		missile.setIlluminated(true);
		currentlyTargeted.add(missile);
	}

	//Cannot use the reference as the missile is already dead at clients
	public void removeTargetMissile(int missileID) {
		DeployedUnit toBeRemoved = null;
		foreach(DeployedUnit controlled in currentlyTargeted) {
			if (controlled.getID() == missileID) {
				toBeRemoved = controlled;
			}
		}

		currentlyTargeted.remove(toBeRemoved);
	}

	override public void checkDestroyedUnits(List<DeployedUnit> destroyedUnits) {
		foreach(DeployedUnit destroyed in destroyedUnits) {
			if (currentlyTargeted.contains(destroyed)) {
				Requests.removeFromIlluminated(this, destroyed);
			}
		}
	}
}