package ru.alphatech.icfpc.game;

import java.util.ArrayList;

import ru.alphatech.icfpc.cards.Attack;
import ru.alphatech.icfpc.cards.Dbl;
import ru.alphatech.icfpc.cards.Get;
import ru.alphatech.icfpc.cards.Help;
import ru.alphatech.icfpc.cards.ICard;
import ru.alphatech.icfpc.cards.K;
import ru.alphatech.icfpc.cards.Put;
import ru.alphatech.icfpc.cards.S;
import ru.alphatech.icfpc.cards.Succ;
import ru.alphatech.icfpc.cards.Zero;
import ru.alphatech.icfpc.game.Batch.OperationType;

/**
 * 
 * TODO 
 * 
 * @author akhmetovlz
 *
 */
public abstract class AbstractPolicy {

	protected ArrayList<Batch> batches = new ArrayList<Batch>();
	
	public AbstractPolicy(){
	}	
	
	public void setRegister(int registerIndex, int num ){
		if( registerIndex < 4) {
			Slot registerSlot = Run.getRegisterByIndex(registerIndex);
			batches.addAll( numberIntoSlotField( registerSlot, num ) );
		}
	}
	
	protected ArrayList<Batch> numberIntoSlotField(Slot targetSlot, int number)
	{	
		ArrayList<Batch> retArray = new ArrayList<Batch>();
		
		IValue targetValue = targetSlot.getValue();
		
		if(targetValue instanceof ICard){
			retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Put(), targetSlot));
		}
		
		Value numTargetValue = (Value) targetValue;
		if( numTargetValue.getValue() == number ){
			return retArray;
		}else
		if( numTargetValue.getValue() > number ){
			retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Put(), targetSlot));
			retArray.add(new Batch(OperationType.SLOT_TO_CARD, new Zero(), targetSlot));
			stupidAlg(0, number, targetSlot);
		}else{
			stupidAlg(numTargetValue.getValue(), number, targetSlot);
		}
		
		return retArray;
	}
	
	
	protected ArrayList<Batch> stupidAlg(int begin, int end, Slot targetSlot){
		ArrayList<Batch> retArray = new ArrayList<Batch>();
		while( begin*2 < end){
			retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Dbl(), targetSlot));
			begin *= 2;
		}
		while( begin != end){
			retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Succ(), targetSlot));
			begin ++;
		}
		return retArray;
	}
	
	protected ArrayList<Batch> smartAlg(int begin, int end, Slot targetSlot){
		ArrayList<Batch> retArray = new ArrayList<Batch>();
		retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Put(), targetSlot));
		retArray.add(new Batch(OperationType.SLOT_TO_CARD, new Zero(), targetSlot));
		while(end >= 2){
			int d = end % 2;
			if( d == 0 ) {
				retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Dbl() , targetSlot));
			} else {
				retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Dbl() , targetSlot));
				retArray.add(new Batch(OperationType.CARD_TO_SLOT, new Succ(), targetSlot));
			}
			end = end / 2; 
		}
		return retArray;
	}
	
	public abstract ArrayList<Batch> getBatches();
}
