package ru.alphatech.icfpc.cards;

import ru.alphatech.icfpc.game.ICFPCException;
import ru.alphatech.icfpc.game.IValue;
import ru.alphatech.icfpc.game.Player;
import ru.alphatech.icfpc.game.Run;
import ru.alphatech.icfpc.game.Value;

public class Attack extends AbstractCard
{
	@Override
	public String getName() {
		return "attack";
	}

	@Override
	public IValue returnValue(final IValue iobj, Player proponent, Player opponent)
	{
		return new AbstractCard()
		{
			@Override
			public String getName() {
				return "";
			}
			
			@Override
			public IValue returnValue(final IValue jobj, Player proponent, Player opponent)
			{
				incAndTest();
				
				return new AbstractCard()
				{
					@Override
					public String getName() {
						return "";
					}
					@Override
					public IValue returnValue(final IValue nobj, Player proponent, Player opponent)
					{
						incAndTest();
						
						if(iobj instanceof Value && nobj instanceof Value)
						{
							int i = ((Value)iobj).getValue();
							int n = ((Value)nobj).getValue();
							
							if(i >= 0 && i <= 255)
							{
								int v = proponent.getSlot(i).getVitality();

								if(n <= v)
								{
									if(jobj instanceof Value)
									{
										int j = ((Value)jobj).getValue();
										
										if(j >= 0 && j <= 255)
										{
											int w = opponent.getSlot(255 - j).getVitality();
											
											if(Run.getAutoMode())
											{
												if(w > 0)
												{
													int wdec = (int) Math.floor(9 * n / 10);
													int resw = w + wdec;

													opponent.getSlot(255 - j).setVitality(resw > 65535 ? 65535 : w);
												}
											}
											else
											{
												if (w > 0)
												{
													int wdec = (int) Math.floor(9 * n / 10);
													int resw = w - wdec;

													opponent.getSlot(255 - j).setVitality(resw < 0 ? 0 : w);
												}
											}											

											return new I();
										}
										else
										{
											throw new ICFPCException();
										}
									}
									else
									{
										throw new ICFPCException();
									}
								}
								else
								{
									throw new ICFPCException();
								}
							}
							else
							{
								throw new ICFPCException();
							}
						}
						else
						{
							throw new ICFPCException();
						}
					}
				};
			}
		};
	}

}
