package com.hero.objects.perks;

import java.util.ArrayList;

import org.jdom.Element;

import com.hero.HeroDesigner;
import com.hero.objects.GenericObject;
import com.hero.objects.List;
import com.hero.objects.Multipower;
import com.hero.objects.modifiers.Modifier;
import com.hero.ui.dialog.GenericDialog;
import com.hero.ui.dialog.ResourcePoolDialog;
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 ResourcePool extends Perk {

	protected static String xmlID = "RESOURCE_POOL";

	private int freePoints = 0;

	public ResourcePool(Element root) {
		super(root, ResourcePool.xmlID);
	}

	@Override
	public String getColumn2Output() {
		String ret = getAlias();
		if ((getSelectedOption() != null)
				&& (getSelectedOption().getAlias().trim().length() > 0)) {
			ret = getSelectedOption().getAlias();
		}
		if ((getName() != null) && (getName().trim().length() > 0)) {
			ret = "<i>" + getName() + ":</i>  " + ret;
		}
		if ((getInput() != null) && (getInput().trim().length() > 0)) {
			ret += " (" + getInput() + ")";
		}
		ret += ": " + (getLevels() + getFreePoints());
		String adderString = getAdderString();
		if (adderString.trim().length() > 0) {
			ret += "; " + adderString;
		}
		ret += getModifierString();
		return ret;
	}

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

	public int getFreePoints() {
		return freePoints;
	}

	/**
	 * Returns the Real/actual cost for the object before any discounts for
	 * being in a List/Framework are taken into account.
	 * 
	 * @return
	 */
	@Override
	public double getRealCostPreList() {
		if (getLevels() == 0) {
			enhancerApplied = null;
			double active = getActiveCost();
			boolean limitationsApplied = false;
			double limitationTotal = 0d;
			for (int i = 0; i < getAssignedModifiers().size(); i++) {
				Modifier mod = getAssignedModifiers().get(i);
				if (mod.getTotalValue() < 0) {
					limitationTotal += mod.getTotalValue();
					limitationsApplied = true;
				}
			}

			List parent = getParentList();
			if (getMainPower() != null) {
				parent = getMainPower().getParentList();
			}
			if (parent != null) {
				ArrayList<Modifier> parentMods = parent.getAssignedModifiers();
				LOOP: for (int i = 0; i < parentMods.size(); i++) {
					Modifier mod = parentMods.get(i);
					if (mod.getTypes().contains("VPP")) {
						continue LOOP;
					}
					if (mod.getXMLID().equals("CHARGES")
							&& (getParentList() instanceof Multipower)) {
						continue LOOP;
					}
					if ((mod.getTotalValue() < 0)
							&& ((GenericObject.findObjectByID(
									assignedModifiers, mod.getXMLID()) == null)
									|| mod.getXMLID().equals("GENERIC_OBJECT")
									|| mod.getXMLID().equals("CUSTOM_MODIFIER") || mod
									.getXMLID().equals("MODIFIER"))) {
						limitationTotal += mod.getTotalValue();
						limitationsApplied = true;
					}
				}
			}
			double ret = active / (1d + Math.abs(limitationTotal));
			if (limitationsApplied) {
				ret = Rounder.roundHalfDown(ret);
			}

			if ((HeroDesigner.getActiveHero() != null)
					&& HeroDesigner.getActiveHero().getRules()
							.multiplierAllowed() && (getMultiplier() != 1)) {
				ret = ret * getMultiplier();
				ret = Rounder.roundHalfDown(ret);
			} else if ((HeroDesigner.getActiveHero() != null)
					&& HeroDesigner.getActiveHero().getRules()
							.multiplierAllowed() && (parent != null)
					&& (parent.getMultiplier() != 1)) {
				ret = ret * parent.getMultiplier();
				ret = Rounder.roundHalfDown(ret);
			}
			if (getQuantity() > 1) {
				double q = getQuantity();
				int doublings = 0;
				while (q > 1d) {
					doublings += 1;
					q = q / 2d;
				}
				ret += doublings * 5;
			}
			return ret;
		} else {
			return super.getRealCostPreList();
		}
	}

	@Override
	public Element getSaveXML() {
		Element root = super.getSaveXML();
		root.setAttribute("FREE_POINTS", "" + getFreePoints());
		return root;
	}

	private void init() {
		baseCost = 0;
		minimumCost = 0;
		maxCost = 999;
		levels = 0;
		minimumLevel = 0;
		levelValue = 1;
		levelCost = 5;
		levelPower = 1;
		minSet = true;
		maxCost = 999;
		maxSet = false;
		freePoints = 0;
		types = new ArrayList<String>();
		userInput = false;
		otherInputAllowed = false;
		optionLbl = "Type";
		abbreviation = "Resource Pool";
		name = "";
		allowsOtherModifiers = true;
		allowsOtherAdders = true;
	}

	@Override
	public void init(Element root) {
		init();
		super.init(root);
	}

	@Override
	public void restoreFromSave(Element root) {
		super.restoreFromSave(root);
		availableModifiers = new ArrayList<Modifier>();
		String check = XMLUtility.getValue(root, "FREE_POINTS");
		if ((check != null) && (check.trim().length() > 0)) {
			try {
				freePoints = Integer.parseInt(check);
			} catch (Exception exp) {
				freePoints = 0;
			}
		}
	}

	public void setFreePoints(int val) {
		freePoints = val;
	}

}