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

public class CIWSModule : Module {
	private int ammo;
	private float range;
	private int roundPerSec;
	private float damagePerRound;
	private float roundSpeed;
	private float hitProbability;

	public CIWSModule(JObject json) : base(json) {
		ammo = (int)json["ammo"];
		range = (float)json["range"];
		roundPerSec = (int)json["roundPerSec"];
		damagePerRound = (float)json["damagePerRound"];
		roundSpeed = (float)json["roundSpeed"];
		hitProbability = (float)json["hitProbability"];

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

	public int getMaxAmmo() {
		return ammo;
	}

	public float getRange() {
		return range;
	}

	public int getRoundPerSec() {
		return roundPerSec;
	}

	public float getDamagePerRound() {
		return damagePerRound;
	}

	public float getRoundSpeed() {
		return roundSpeed;
	}

	public float getHitProbability() {
		return hitProbability;
	}

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

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

		return array;
	}

	override public void updateClasses() {
	}

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

public class CIWSModuleData : ModuleData{
	private int ammoLeft;
	private bool hasFiredInThisTick = false;

	public CIWSModuleData(int parent, Module template) : base(parent, template) {
		ammoLeft = ((CIWSModule)template).getMaxAmmo();
	}

	public void fire(DeployedUnit target, float delta, float distance) {
		if (hasFiredInThisTick) {
			return;
		}

		hasFiredInThisTick = true;

		int count = 0;

		for (int i = 0; i < ((CIWSModule)template).getRoundPerSec() * delta && i < ammoLeft; i++) {
			if (Random.value < ((CIWSModule)template).getHitProbability()) {
				count ++;
			}
			ammoLeft --;
		}

		//no requests needed, as bullets are not shared with the clients
		GameController.addBullets(new Bullets(count, distance / (((CIWSModule)template).getRoundSpeed() + target.getcurrentSpeed()), ((CIWSModule)template).getDamagePerRound(), target, template.getName()));
	}

	override public bool isFiring() {
		return hasFiredInThisTick;
	}

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

	override public void updateTime(float delta) {
		hasFiredInThisTick = false;
	}
}