/***
 * Specs Engine v6: Spectacles Saga Game Engine
  *           Copyright (c) 2017 Power-Command
***/

class ItemUsable
{
	constructor(itemID)
	{
		if (!(itemID in Game.items))
			throw new ReferenceError(`no such item '${itemID}'`);

		this.givesExperience = false;
		this.isUnlimited = false;
		this.itemDef = clone(Game.items[itemID]);
		if (!('rank' in this.itemDef.action))
			this.itemDef.action.rank = Game.defaultItemRank;
		this.isGroupCast = false;
		this.itemID = itemID;
		this.name = this.itemDef.name;
		this.useAiming = false;
		this.allowDeadTarget = 'allowDeadTarget' in this.itemDef
			? this.itemDef.allowDeadTarget
			: false;
		this.usesLeft = 'uses' in this.itemDef ? this.itemDef.uses : 1;
	}

	clone()
	{
		var newCopy = new ItemUsable(this.itemID);
		newCopy.usesLeft = this.usesLeft;
		return newCopy;
	}

	defaultTargets(user)
	{
		var target = user;
		var allies = user.battle.alliesOf(user);
		if (this.allowDeadTarget && from(allies).any(unit => !unit.isAlive())) {
			target = from(allies)
				.where(unit => !unit.isAlive())
				.sample(1).first();
		}
		return [ target ];
	}

	getRank()
	{
		return 'rank' in this.itemDef.action ? this.itemDef.action.rank
			: Game.defaultItemRank;
	}

	isUsable(user, stance = Stance.Attack)
	{
		return (this.isUnlimited || this.usesLeft > 0)
			&& stance == Stance.Attack;
	}

	mpCost(user)
	{
		return 0;
	}

	peekActions()
	{
		return [ this.itemDef.action ];
	}

	use(unit, targets)
	{
		if (!this.isUsable(unit, unit.stance))
			throw new Error(`${unit.name} tried to use unusable item ${this.name}`);
		--this.usesLeft;
		term.print(`${unit.name} is using ${this.name}`,
			`targ: ${targets.length > 1 ? "[multi]" : targets[0].name}`,
			`left: ${this.usesLeft}`);
		var eventData = { item: clone(this.itemDef) };
		unit.raiseEvent('useItem', eventData);
		unit.battle.notifyAIs('itemUsed', unit.id, this.itemID, from(targets).select(v => v.id).toArray());
		return [ eventData.item.action ];
	}
}
