package com.hero.objects.perks;

import java.io.File;
import java.util.ArrayList;
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.enhancers.Enhancer;
import com.hero.ui.dialog.FollowerDialog;
import com.hero.ui.dialog.GenericDialog;
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 Follower extends Perk {

	private static String xmlID = "FOLLOWER";

	private int overCost;

	private int overVal;

	private int multiplierCost;

	private int multiplierVal;

	private int multiples;

	private int basePoints;

	private int disadPoints;

	private String filePath;

	private Date fileAssociationLastCheck;

	public Follower(Element template) {
		super(template, Follower.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;
	}

	public int getBasePoints() {
		checkFileAssociation();
		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) {
		FollowerDialog dialog = new FollowerDialog(this, isNew, isPower);
		return dialog;
	}

	public int getDisadPoints() {
		checkFileAssociation();
		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 (getBasePoints() + getDisadPoints() <= charTotal || HeroDesigner.getActiveTemplate().is6E()) {
			total += getBasePoints() / 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 = getMultiples();
		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 = "Follower";
		alias = "Follower";
		baseCost = 0;
		levelCost = 1;
		levelValue = 5;
		minimumCost = 1;
		maxCost = 10;
		overCost = 1;
		overVal = 1;
		multiplierCost = 5;
		multiplierVal = 2;
		multiples = 1;
		basePoints = 0;
		disadPoints = 0;
		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;
				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;
	}
}