package Manager;

import Encoding.vl64;

public class Pathfinding implements Runnable
{
    public Room rm;
    
            int idroom;
            int iduser;

            int x;
            int y;

            int xold;
            int yold;

            int cx;
            int cy;

            int rotation;

    public Pathfinding(int x, int y, Room rm, int idroom, int iduser){
        this.x = x;
        this.y = y;
        this.rm = rm;
        this.idroom = idroom;
        this.iduser = iduser;

        rm.getposizione(iduser);
        xold = rm.getx();
        yold = rm.gety();
        cx = xold;
        cy = yold;

    }

    public void path(int x, int y)
    {
        while(cx != x || cy != y)
            {
                  if(cy < y){
                     cy++;
                   }

                   if(cx < x){
                     cx++;
                   }

                   if(cy > y){
                     cy--;
                   }

                   if(cx > x){
                     cx--;
                   }

            if (xold > cx && yold > cy)
                rotation = 7;
            else if(xold < cx && yold < cy)
                rotation = 3;
            else if(xold > cx && yold < cy)
                rotation = 5;
            else if(xold < cx && yold > cy)
                rotation = 1;
            else if(xold > cx)
                rotation = 6;
            else if(xold < cx)
                rotation = 2;
            else if(yold < cy)
                rotation = 4;
            else if(yold > cy)
                rotation = 0;
                  rm.sendroom(idroom, "@b" + "I" + vl64.Encode(rm.getidusroom(iduser)) + vl64.Encode(xold) + vl64.Encode(yold) + "0.0" + (char)2 + vl64.Encode(rotation) + vl64.Encode(rotation) + "//mv " + cx + "," + cy + ",0.0//" + (char)2);

                  rm.posizione(iduser,cx,cy,rotation);
            try{
            Thread.sleep(500); //Attesa mezzo secondo
            }catch (Exception con)
            {
                 con.printStackTrace();
            }
                  xold = cx;
                  yold = cy;
            }

            rm.sendroom(idroom, "@b" + "I" + vl64.Encode(rm.getidusroom(iduser)) + vl64.Encode(x) + vl64.Encode(y) + "0.0" + (char)2 + vl64.Encode(rotation) + vl64.Encode(rotation) + "///" + (char)2);
            rm.posizione(iduser,x,y,rotation);
    }

    public void run()
    {
         path(x, y);
    }
         
}
