/**
 * Copyright © 2010, Res Interactive, LLC. All Rights Reserved.
 */
package com.tootsville.items;

import java.math.BigDecimal;

import org.starhope.appius.except.UserDeadException;
import org.starhope.appius.game.AppiusClaudiusCaecus;
import org.starhope.appius.game.inventory.InventoryItem;
import org.starhope.appius.game.inventory.effects.SimpleArmour;
import org.starhope.appius.user.UserTransients;
import org.starhope.appius.util.AcceptsMetronomeTicks;

/**
 * WRITEME: Document this type.
 *
 * @author brpocock@star-hope.org
 *
 */
public class GrowPotion extends SimpleArmour implements
		AcceptsMetronomeTicks {

	/**
	 * the millisecond accumulator for the health decrease
	 */
	private int timeAcc = 0;

	/**
	 * Whether to stop the metronome listener after this tick
	 */
	private boolean lastTick = false;

	/**
	 * @param theItem the item being a grow potion
	 */
	public GrowPotion (final InventoryItem theItem) {
		super (theItem);
		// TODO Auto-generated constructor stub brpocock@star-hope.org
	}

	/**
	 * @see org.starhope.appius.util.HasName#getName()
	 */
	@Override
	public String getName () {
		StringBuilder s = new StringBuilder ();
		s.append ("GrowPotion effect on item ");
		s.append (item.getGenericItem ().getTitle ());
		s.append (" owned by ");
		s.append (item.getOwner ().getAvatarLabel ());
		return s.toString ();
	}

	/**
	 * @see org.starhope.appius.game.inventory.ItemEffects#onDeEquip()
	 */
	@Override
	public void onDeEquip () {
		super.onDeEquip ();
		UserTransients.getEffects (item.getOwner ()).heightScalar = 1;
		item.getOwner ().sendWardrobe ();
		lastTick = true;
	}
	/**
	 * @see org.starhope.appius.game.inventory.ItemEffects#onEquip()
	 */
	@Override
	public void onEquip () {
		super.onEquip ();
		UserTransients.getEffects (item.getOwner ()).heightScalar = 1.5;
		item.getOwner ().sendWardrobe ();
		lastTick = false;
		AppiusClaudiusCaecus.add (this);
	}

	/**
	 * @see org.starhope.appius.util.AcceptsMetronomeTicks#tick(long,
	 *      long)
	 */
	@Override
	public void tick (final long currentTime, final long deltaTime)
			throws UserDeadException {
		if (item.isActive ()) {
			timeAcc += deltaTime;
			item.changeHealth ( - (timeAcc / 1000));
			timeAcc %= 1000;
		}
		if (item.getHealth ().compareTo (BigDecimal.ONE) <= 0) {
			item.setActive (false);
			onDeEquip ();
			item.destroy ();
		}
		if (lastTick) {
			AppiusClaudiusCaecus.remove (this);
		}
	}
}
