package ia;

import java.awt.Point;
import java.util.ArrayList;
import java.util.List;

import model.Direction;
import model.Grid;
import model.Position;
import captors.ExtendedMovement;


public class Exploitation {

	private int ID;
	private Position position;
	private Grid grid;
	private List<Point> path;
	private ExtendedMovement movement;
	private boolean error;
	
	public Exploitation(Position position,Grid grid,ExtendedMovement movement){
		this.position=position;
		this.grid=grid;
		this.movement=movement;
		this.error=false;
		//TODO récupérer un ID par bluetooth
	}
	
	
	public void solve(Point destination){
		//TODO écouter si l'autre robot dit qu'il a un problème
		Point nextPoint= null;
		Point begin = null;
		
		IA ia = new IA(this.position, this.grid);
		Solution sol = ia.goTo(destination.x, destination.y);
		this.getPath(sol);
		
		while (!this.path.isEmpty()){
			//si pb calcul du nouveau chemin
			if (this.error){
				ia = new IA(this.position, this.grid);
				sol = ia.goTo(destination.x, destination.y);
				this.getPath(sol);
				this.error=false;
			}
			
			nextPoint = this.path.remove(0);
			begin = this.position.getPoint();
			this.movement.turn(Direction.getDirectionBetween(this.position.getPoint(), nextPoint));
			this.movement.straightForward();
			
			//si le robot n'arrive pas à la bonne case
			if (!this.position.getPoint().equals(nextPoint)){
				//TODO dire à l'autre robot qu'il y a un problème et pas de mur sur le chemin parcouru	
				this.setChanges(begin,this.position.getPoint(),this.position.getDirection());
				this.error=true;
			}
		}
	}
	
	
	
	
	//Get the right path according to the ID
	public void getPath(Solution sol){
		if (sol.alonePath != null) {
			if (this.ID==1)
				this.path = sol.alonePath;
			else if (this.ID==2)
				this.path = new ArrayList<Point>();
		} 
		else {
			if (this.ID==1)
				this.path = sol.otherCoopPath;
			else if (this.ID==2)
				this.path = sol.myCoopPath;
		}
	}
	
	
	//Met à jour les murs si on arrive pas à la bonne case
	public void setChanges(Point start, Point dest,Direction dir){
		this.grid.setTile(dest.x,dest.y,dir,WallState.Wall);
		switch (dir){
		case NORTH:
			for (int x=start.x; x=dest.x+1;x--){
				this.grid.setTile(x, start.y, dir, WallState.Empty);
			}
			break;
		case SOUTH:
			for (int x=start.x; x=dest.x-1;x++){
				this.grid.setTile(x, start.y, dir, WallState.Empty);
			}
			break;	
		case EAST:
			for (int y=start.y; y=dest.y-1;y--){
				this.grid.setTile(start.x,y, dir, WallState.Empty);
			}
			break;
		case WEST:
			for (int y=start.y; y=dest.y+1;y++){
				this.grid.setTile(start.x,y, dir, WallState.Empty);
			}
			break;
		}
	}
}

@@ -143,24 +143,48 @@
 l.Position;%0A
+import model.WallState;%0A
 import capto
@@ -2216,17 +2216,15 @@
 x; x
-=
+%3E
 dest.x
-+1
 ;x--
@@ -2340,17 +2340,15 @@
 x; x
-=
+%3C
 dest.x
--1
 ;x++
@@ -2464,17 +2464,15 @@
 y; y
-=
+%3E
 dest.y
--1
 ;y--
@@ -2586,17 +2586,15 @@
 y; y
-=
+%3C
 dest.y
-+1
 ;y++

debug imports