package com.hero.objects.powers;

import java.io.File;
import java.util.Date;

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.modifiers.Modifier;
import com.hero.ui.dialog.DuplicationDialog;
import com.hero.ui.dialog.GenericDialog;
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 Duplication extends Power {

	private static String xmlID = "DUPLICATION";

	private int overCost = 1;

	private int overVal = 1;

	private int multiplierCost = 5;

	private int multiplierVal = 2;

	private int multiples = 1;

	private int points = 0;

	private String filePath;

	private Date fileAssociationLastCheck;

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

	private void checkFileAssociation() {
		if (filePath == null) {
			return;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			file = new File(HeroDesigner.getInstance().getPrefs().getSaveDir()
					+ File.separator + file.getName());
		}
		if (!file.exists()) {
			return;
		}

		if (file.lastModified() > fileAssociationLastCheck.getTime()) {
			setFilePath(filePath);
		}
	}

	public void clearFilePath() {
		filePath = null;
		fileAssociationLastCheck = null;
	}

	@Override
	public String getColumn2Output() {
		String ret = getAlias();
		if ((getName() != null) && (getName().trim().length() > 0)) {
			ret = "<i>" + getName() + ":</i>  " + ret;
		}
		ret += " (";
		if (multiples > 1) {
			ret += "creates " + multiples + " ";
			ret += points + "-point Duplicates)";
		} else {
			ret += "creates " + points + "-point form)";
		}
		String adderString = getAdderString();
		if (adderString.trim().length() > 0) {
			ret += ", ";
			ret += adderString;
		}
		ret += getModifierString();
		return ret;
	}

	@Override
	public String getDamageDisplay() {
		return "";
	}

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

	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;
	}

	public int getPoints() {
		checkFileAssociation();
		return points;
	}

	@Override
	public Element getSaveXML() {
		Element root = super.getSaveXML();
		root.setAttribute("NUMBER", "" + getMultiples());
		root.setAttribute("POINTS", "" + points);
		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 (points <= charTotal || HeroDesigner.getActiveTemplate().is6E()) {
			total += points / levelValue * levelCost;
		} else {
			Modifier altered = null;
			for (Modifier mod : availableModifiers) {
				if (mod.getXMLID().equals("ALTEREDDUPLICATES")) {
					altered = mod.clone();
					break;
				}
			}
			if (altered != null) {
				boolean added = false;
				OUTER: for (Modifier mod : getAssignedModifiers()) {
					if (mod.getXMLID().equals(altered.getXMLID())) {
						altered = mod;
						added = true;
						if (!altered.getSelectedOption().equals("ALL")) {
							for (Adder op : altered.getOptions()) {
								if (op.getXMLID().equals("ALL")) {
									altered.setSelectedOption(op);
									break OUTER;
								}
							}
						}
					}
				}
				if (!added) {
					if (!altered.getSelectedOption().equals("ALL")) {
						INNER: for (Adder op : altered.getOptions()) {
							if (op.getXMLID().equals("ALL")) {
								altered.setSelectedOption(op);
								break INNER;
							}
						}
					}
					getAssignedModifiers().add(altered);
				}
			}

			int allowedBase = charTotal;
			int overBase = points - 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();
			}
		}
		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().contains("DEFENSE")
				&& (HeroDesigner.getActiveHero() != null)) {
			if (GenericObject.findObjectByID(HeroDesigner.getActiveHero()
					.getPowers(), "AUTOMATON") != null) {
				Automaton auto = (Automaton) GenericObject.findObjectByID(
						HeroDesigner.getActiveHero().getPowers(), "AUTOMATON");
				if (auto.getSelectedOption().getXMLID().toUpperCase()
						.startsWith("NOSTUN")) {
					total = total * auto.getDefenseCostMultiplier();
				}
			}
		}
		return total;
	}

	@Override
	protected void init(Element element) {
		display = "Duplication";
		alias = "Duplication";
		baseCost = 0;
		levelCost = 1;
		levelValue = 5;
		minimumCost = 1;
		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, "POINTS");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				points = Integer.parseInt(check);
			} catch (Exception exp) {
			}
		}
		check = XMLUtility.getValue(root, "FILE_ASSOCIATION");
		if ((check != null) && (check.trim().length() > 0)) {
			setFilePath(check);
		}
	}

	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 {
						points = Integer.parseInt(check);
					} catch (Exception exp) {
					}
				}
				check = XMLUtility.getValue(basic, "DISAD_POINTS");
				if ((check != null) && (check.trim().length() > 0)) {
					try {
						points += Integer.parseInt(check);
					} catch (Exception exp) {
					}
				}
				check = XMLUtility.getValue(basic, "EXPERIENCE");
				if ((check != null) && (check.trim().length() > 0)) {
					try {
						points += Integer.parseInt(check);
					} catch (Exception exp) {
					}
				}
				filePath = path;
				fileAssociationLastCheck = new Date();
			} 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;
	}

	public void setPoints(int val) {
		points = val;
	}
}