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

public class StorageModule : Module {
	private float loadingTime;

	public StorageModule(JObject json) : base(json) {
		loadingTime = (float)json["loadingTime"];

		sprite = Resources.Load("Sprites/Modules/Storage/" + getUniqueName(), typeof(Sprite)) as Sprite;
	}

	public float getLoadingTime() {
		return loadingTime;
	}

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

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

		return array;
	}

	override public void updateClasses() {
	}

	override public ModuleData getData(int parent) {
		return new StorageModuleData(parent, this);
	}
}

public class StorageModuleData : ModuleData {
	private float waitingTime;
	private List<StoredUnit> storedUnits;

	public StorageModuleData(int parent, Module template) : base(parent, template) {
		storedUnits = new List<StoredUnit>();
	}

	public StoredUnit prepareLoading(Class unitClass) {
		foreach(StoredUnit unit in storedUnits) {
			if (unit.getClass() == unitClass && !unit.isBeingLoaded()) {
				return unit;
			}
		}

		return null;
	}

	public int loadInto(StoredUnit unit, Class ammoType, int count) {
		if (waitingTime > 0.0f) {
			return 0;
		}

		int loaded = 0;
		StoredUnit toBeRemoved = null;
		foreach(StoredUnit ammoUnit in storedUnits) {
			if(!ammoUnit.isBeingLoaded() && ammoUnit.getClass() == ammoType) {
				toBeRemoved = ammoUnit;
				loaded ++;

				unit.store(ammoUnit);

				waitingTime += ((StorageModule)template).getLoadingTime();

				break;
			}
		}

		if (toBeRemoved != null) {
			storedUnits.Remove(toBeRemoved);
		}

		return loaded;
	}

	//should only be called from StoredUnit's changeStore
	public void addToStored(StoredUnit stored) {
		storedUnits.Add(stored);
	}

	public void removeFromStored(StoredUnit unit) {
		storedUnits.Remove(unit);
	}

	public void removeFromStoredIfExists(int unitID) {
		StoredUnit unit = null;

		foreach(StoredUnit stored in storedUnits) {
			if (stored.getID() == unitID) {
				unit = stored;
			}
		}

		if (unit == null) {
			return;
		}

		storedUnits.Remove(unit);
	}

	public int getNumberStored(Class unitClass) {
		int total = 0;

		foreach(StoredUnit stored in storedUnits) {
			if(!stored.isBeingLoaded() && stored.getClass() == unitClass) {
				total++;
			}
		}

		return total;
	}

	override public void deployUnit(int storedUnitID) {
		Debug.LogError("This module cannot deploy units");
	}

	override public void updateTime(float delta) {
		waitingTime = Mathf.Max(0.0f, waitingTime - delta);
	}
}