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

public enum MissileTechnique {SeaSkimming = 0, Direct = 1};

public class GuidanceModule : Module {
	private MissileTechnique technique;
	private List<ClassType> listCanHit;
	private float failProbability; //per sec
	private float distanceRadarOn; //when the missile should turn its radar on
	private bool needsMissileControl;
	private bool needsTargetIlluminated;

	public GuidanceModule(JObject json) : base(json) {
		this.technique = (MissileTechnique)((int)(json["missileTechnique"]) - 1);

		this.listCanHit = new List<ClassType>();
		foreach (int classType in json["canHit"]) {
			listCanHit.Add((ClassType)(classType - 1));
		}

		this.failProbability = (float)json["failProbability"];

		JToken token;
		if (json.TryGetValue("distanceRadarOn", out token)) {
			distanceRadarOn = (float)json["distanceRadarOn"];
		}
		else {
			distanceRadarOn = float.MaxValue;
		}


		if (json.TryGetValue("needsMissileControl", out token)) {
			needsMissileControl = (bool)json["needsMissileControl"];
		}
		else {
			needsMissileControl = false;
		}

		if (json.TryGetValue("needsTargetIlluminated", out token)) {
			needsTargetIlluminated = (bool)json["needsTargetIlluminated"];
		}
		else {
			needsTargetIlluminated = false;
		}

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

	public MissileTechnique getMissileTechnique() {
		return technique;
	}

	public bool canHit(ClassType classType) {
		return (listCanHit.Contains(classType));
	}

	public float getFailProbability(float delta) {
		return 1 - Mathf.Pow(1 - failProbability, delta);
	}

	public float getDistanceRadarOn() {
		return distanceRadarOn;
	}

	public bool getNeedsMissileControl() {
		return needsMissileControl;
	}

	public bool getNeedsTargetIlluminated() {
		return needsTargetIlluminated;
	}

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

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

		return array;
	}

	override public void updateClasses() {
	}

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

public class GuidanceModuleData : ModuleData {
	public GuidanceModuleData(int parent, Module template, Vector position) : base(parent, template, position) {
	}
}
