package it.playfellas.superapp.logic.slave.game23;

import android.util.Log;

import com.squareup.otto.Subscribe;

import it.playfellas.superapp.events.EventFactory;
import it.playfellas.superapp.events.game.BeginStageEvent;
import it.playfellas.superapp.events.game.YourTurnEvent;
import it.playfellas.superapp.events.tile.ClickedTileEvent;
import it.playfellas.superapp.events.tile.StackClickEvent;
import it.playfellas.superapp.logic.db.TileSelector;
import it.playfellas.superapp.logic.tiles.Tile;
import it.playfellas.superapp.network.TenBus;

/**
 * Created by affo on 02/09/15.
 */
public class Slave3Controller extends Slave23Controller {
    private static final String TAG = Slave3Controller.class.getSimpleName();
    private TowerDispenser dispenser;
    private Tile[] stack;

    public Slave3Controller(TileSelector ts) {
        super();
        this.dispenser = new TowerDispenser(ts);

        TenBus.get().register(this);
    }

    @Override
    protected void onBeginStage(BeginStageEvent e) {
    }

    private int emptySlot() {
        int i = 0;
        for (; i < stack.length && stack[i] != null; i++) ;
        return i;
    }

    @Override
    protected synchronized boolean isTileRight(Tile t) {
        int i = emptySlot();
        if (i >= stack.length) {
            Log.d(TAG, "Stack exceeded!");
            return false;
        }

        return getBaseTiles()[i].equals(t);
    }

    @Override
    protected TileDispenserWBaseTiles getDispenser() {
        return dispenser;
    }

    @Subscribe
    public void onConveyorClicked(ClickedTileEvent e) {
        TenBus.get().post(EventFactory.push(e.getTile()));
    }

    @Subscribe
    public synchronized void onStackClicked(StackClickEvent e) {
        int i = emptySlot() - 1;
        boolean wrongPop = false;
        if (i >= 0) {
            wrongPop = getBaseTiles()[i].equals(stack[i]);
        }
        TenBus.get().post(EventFactory.pop(wrongPop));
    }

    @Subscribe
    public synchronized void onStackUpdate(YourTurnEvent e) {
        this.stack = e.getStack();
    }
}

@@ -969,16 +969,29 @@
 otected 
+synchronized 
 void onB
@@ -1017,24 +1017,24 @@
 eEvent e) %7B%0A
-
     %7D%0A%0A    p
@@ -1234,39 +1234,35 @@
 e t) %7B%0A        i
-nt i = 
+f (
 emptySlot();%0A   
@@ -1256,31 +1256,16 @@
 tySlot()
-;%0A        if (i
  %3E= stac
@@ -1337,32 +1337,32 @@
   return false;%0A
-
         %7D%0A%0A     
@@ -1352,24 +1352,305 @@
 %0A        %7D%0A%0A
+        int i = 0;%0A        do %7B%0A            Tile st = stack%5Bi%5D;%0A%0A            if (st == null) %7B%0A                break;%0A            %7D%0A%0A            if (!st.equals(getBaseTiles()%5Bi%5D)) %7B%0A                return false;%0A            %7D%0A%0A            i++;%0A        %7D while (i %3C stack.length);%0A%0A
         retu

fix in is tile right logic