package rpgEngine.Logic.Game;

import java.util.List;
import java.util.Random;

import rpgEngine.Data.Abstract.Enemy.Enemy;
import rpgEngine.Data.Abstract.Party.HumanPlayer;

public class EnemyFightUse {
	private List<HumanPlayer> humanPlayers;
	private Enemy enemy;
	
	public static final int TYPE_ATTACK = 0;
	public static final int TYPE_MAGIC = 1;
	
	
	public EnemyFightUse(Enemy e, List<HumanPlayer> p) {
		enemy = e;
		humanPlayers = p;
	}
	
	
	public String fight() {
		String resultMessage = "";
		Random random = new Random();
		Integer playerIndex = 0;
		HumanPlayer player = null;
		Integer attackType = TYPE_ATTACK;
		Double randomMultiplier = 1.0;
		Double skillMultiplier = 1.0;
		Integer damagePoints = 0;
		
		//get target
		while(player == null) {
			playerIndex = random.nextInt(humanPlayers.size());
			
			player = humanPlayers.get(playerIndex);
			
			if(player.getHP() <= 0) {
				player = null;
			}
		}
		
		//get attack type
		if(random.nextDouble() < enemy.getAttackChance()) {
			attackType = TYPE_ATTACK;
		}
		else {
			attackType = TYPE_MAGIC;
		}
		
		//miss check
		if(random.nextDouble() > 0.95) {
			resultMessage = "Enemy Attack Missed!";
			return resultMessage;
		}
		
		//Random Multiplier
		randomMultiplier = 0.8 + (Math.random() * (1.2 - 0.8));
		
		//Skill Multiplier
		if(attackType == TYPE_ATTACK) {
			skillMultiplier = ((double)enemy.getAttack()) / ((double)enemy.getSkill());
		}
		else {
			skillMultiplier = ((double)enemy.getSkill()) / ((double)enemy.getAttack());
		}
	
		if(skillMultiplier < 0.8) {
			skillMultiplier = 0.8;
		}
		if(skillMultiplier > 1.2) {
			skillMultiplier = 1.2;
		}
		
		//Determine Damage
		if(attackType == TYPE_ATTACK) {
			damagePoints = (int)((double)enemy.getAttack() * randomMultiplier * skillMultiplier);
		}
		else {
			damagePoints = (int)((double)enemy.getSkill() * randomMultiplier * skillMultiplier);
		}
		
		//Defense Consideration
		if(attackType == TYPE_ATTACK) {
			damagePoints = damagePoints - (player.getDefense() / 2);
		}
		else {
			damagePoints = damagePoints - (player.getBarrier() / 2);
		}
		
		if(damagePoints <= 0) {
			damagePoints = 1;
		}
		
		player.setHP(player.getHP() - damagePoints);
		
		if(player.getHP() < 0) {
			player.setHP(0);
		}
		
		resultMessage = damagePoints + " damage to " + player.getName() + "!";
		
		return resultMessage;
	}
	
	
}
