package com.hero.objects.perks;

import java.io.File;
import java.util.ArrayList;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.hero.HeroDesigner;
import com.hero.objects.Adder;
import com.hero.objects.GenericObject;
import com.hero.objects.enhancers.Enhancer;
import com.hero.ui.dialog.GenericDialog;
import com.hero.ui.dialog.VehicleDialog;
import com.hero.util.Rounder;
import com.hero.util.XMLUtility;

/**
 * Copyright (c) 2000 - 2005, CompNet Design, Inc. All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, is prohibited unless the following conditions are met: 1.
 * Express written consent of CompNet Design, Inc. is obtained by the developer.
 * 2. Redistributions must retain this copyright notice. THIS SOFTWARE IS
 * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * @author CompNet Design, Inc.
 * @version $Revision$
 */

public class Vehicle extends Perk {
	private static String xmlID = "VEHICLE_BASE";

	private int overCost = 1;

	private int overVal = 1;

	private int multiplierCost = 5;

	private int multiplierVal = 2;

	private int multiples = 1;

	private int basePoints = 0;

	private int disadPoints = 0;

	private String filePath;

	public Vehicle(Element template) {
		super(template, Vehicle.xmlID);
	}

	public void clearFilePath() {
		filePath = null;
	}

	public int getBasePoints() {
		return basePoints;
	}

	@Override
	public String getColumn2Output() {
		String ret = getAlias();
		if ((getName() != null) && (getName().trim().length() > 0)) {
			ret = "<i>" + getName() + ":</i>  " + ret;
		}
		String adderString = getAdderString();
		if (adderString.trim().length() > 0) {
			ret += " (";
			ret += adderString;
			ret += ")";
		}
		ret += getModifierString();
		if ((getEndUsage() > 0)
				&& (GenericObject.findObjectByID(HeroDesigner.getActiveHero()
						.getPowers(), "ENDURANCERESERVE") != null)
				&& (GenericObject.findObjectByID(getAllAssignedModifiers(),
						"ENDRESERVEOREND") == null)
				&& !HeroDesigner.getInstance().getPrefs().useWG()) {
			if (getUseENDReserve()) {
				ret += " (uses END Reserve)";
			} else {
				ret += " (uses Personal END)";
			}
		}
		return ret;
	}

	@Override
	public GenericDialog getDialog(boolean isNew, boolean isPower) {
		VehicleDialog dialog = new VehicleDialog(this, isNew, isPower);
		return dialog;
	}

	public int getDisadPoints() {
		return disadPoints;
	}

	public String getFilePath() {
		return filePath;
	}

	public int getMultiples() {
		return multiples;
	}

	public int getMultiplierCost() {
		return multiplierCost;
	}

	public int getMultiplierVal() {
		return multiplierVal;
	}

	public int getOverCost() {
		return overCost;
	}

	public int getOverVal() {
		return overVal;
	}

	@Override
	public Element getSaveXML() {
		Element root = super.getSaveXML();
		root.setAttribute("NUMBER", "" + getMultiples());
		root.setAttribute("BASEPOINTS", "" + basePoints);
		root.setAttribute("DISADPOINTS", "" + disadPoints);
		if (filePath != null) {
			root.setAttribute("FILE_ASSOCIATION", filePath);
		}
		return root;
	}

	@Override
	public double getTotalCost() {
		enhancerApplied = null;
		double total = getBaseCost();
		int charTotal = HeroDesigner.getActiveHero().getBasePoints()
				+ HeroDesigner.getActiveHero().getDisadPoints()
				+ HeroDesigner.getActiveHero().getExperience();
		if (HeroDesigner.getActiveTemplate().is6E()) {
			charTotal -= HeroDesigner.getActiveHero().getDisadPoints();
		}
		if (basePoints + disadPoints <= charTotal || HeroDesigner.getActiveTemplate().is6E()) {
			total += basePoints / levelValue * levelCost;
		} else {
			int allowedBase = charTotal >= getBasePoints() ? getBasePoints()
					: charTotal;
			int overBase = getBasePoints() + getDisadPoints() - charTotal;
			total += ((double) overBase / (double) overVal) * overCost;
			total += (allowedBase / levelValue) * levelCost;
		}
		int numMultiples = 0;
		double check = multiples;
		while (check > 1d) {
			check = check / getMultiplierVal();
			numMultiples++;
		}
		total += numMultiples * getMultiplierCost();
		for (Adder ad : getAssignedAdders()) {
			if (ad.getRealCost() > 0) {
				total += ad.getRealCost();
			}
		}
		total = Rounder.roundHalfDown(total);
		if ((total < minimumCost) && minSet) {
			total = getMinimumCost();
		} else if ((total > maxCost) && maxSet) {
			total = getMaxCost();
		}
		for (Adder ad : getAssignedAdders()) {
			if (ad.getRealCost() < 0) {
				total += ad.getRealCost();
			}
		}
		if ((getTypes() != null) && (getTypes().size() > 0)) {
			ArrayList<GenericObject> enhancers = HeroDesigner.getActiveHero()
					.getSkills();
			OUTER: for (GenericObject o : enhancers) {
				if (o instanceof Enhancer) {
					Enhancer enhancer = (Enhancer) o;
					for (String s : getTypes()) {
						if (enhancer.appliesToType(s)) {
							enhancerApplied = enhancer;
							// just take the first match and leave it at
							// that...
							if (total > enhancer.getCostSavings()) {
								total -= enhancer.getCostSavings();
							} else if (total > 0) {
								total = 1;
							}
							break OUTER;
						}
					}
				}
			}
		}
		return total;
	}

	@Override
	protected void init(Element element) {
		display = "Vehicles & Bases";
		alias = "Vehicle";
		baseCost = 0;
		levelCost = 1;
		levelValue = 5;
		minimumCost = 1;
		maxCost = 10;
		super.init(element);
		String check = XMLUtility.getValue(element, "OVERCOST");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				overCost = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(element, "OVERVAL");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				overVal = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(element, "MULTIPLIERCOST");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				multiplierCost = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(element, "MULTIPLIERVAL");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				multiplierVal = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
	}

	@Override
	public void restoreFromSave(Element root) {
		super.restoreFromSave(root);
		String check = XMLUtility.getValue(root, "NUMBER");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				multiples = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(root, "BASEPOINTS");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				basePoints = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(root, "DISADPOINTS");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				disadPoints = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(root, "FILE_ASSOCIATION");
		if ((check != null) && (check.trim().length() > 0)) {
			setFilePath(check);
		}
	}

	public void setBasePoints(int basePoints) {
		this.basePoints = basePoints;
	}

	public void setDisadPoints(int disadPoints) {
		this.disadPoints = disadPoints;
	}

	public void setFilePath(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file = new File(HeroDesigner.getInstance().getPrefs().getSaveDir()
					+ File.separator + file.getName());
		}
		if (file.exists() && file.canRead()) {
			try {
				SAXBuilder builder = new SAXBuilder(false);
				Document doc = builder.build(file);
				builder = null;
				Element root = doc.getRootElement();
				Element basic = root.getChild("BASIC_CONFIGURATION");
				String check = XMLUtility.getValue(basic, "BASE_POINTS");
				if ((check != null) && (check.trim().length() > 0)) {
					try {
						basePoints = Integer.parseInt(check);
					} catch (Exception exp) {
					}
				}
				check = XMLUtility.getValue(basic, "DISAD_POINTS");
				if ((check != null) && (check.trim().length() > 0)) {
					try {
						disadPoints = Integer.parseInt(check);
					} catch (Exception exp) {
					}
				}
				check = XMLUtility.getValue(basic, "EXPERIENCE");
				if ((check != null) && (check.trim().length() > 0)) {
					try {
						basePoints += Integer.parseInt(check);
					} catch (Exception exp) {
					}
				}
				filePath = path;
			} catch (Exception exp) {

			}
		}
	}

	public void setMultiples(int multiples) {
		this.multiples = multiples;
	}

	public void setMultiplierCost(int multiplierCost) {
		this.multiplierCost = multiplierCost;
	}

	public void setMultiplierVal(int multiplierVal) {
		this.multiplierVal = multiplierVal;
	}

	public void setOverCost(int overCost) {
		this.overCost = overCost;
	}

	public void setOverVal(int overVal) {
		this.overVal = overVal;
	}
}