program quinze_web;

{$mode objfpc}

uses
  BrowserAppJSClassesSysUtilsWeb,
  fifteenengine;

type

  { TMyApplication }

  TMyApplication class(TBrowserApplication)
    btNewTJSHTMLButtonElement;
    FCanvasTJSHTMLCanvasElement;
    FCtxTJSCanvasRenderingContext2D;
    procedure BindElements;
    function OnFormKeyPress(kTJSKeyBoardEvent): Boolean;
    function NewGame(aEventTJSMouseEvent):boolean;
    procedure DrawBoard;
  protected
    procedure DoRunoverride;
  public
  end;

procedure TMyApplication.BindElements;
var
  i:integer;
  s:string;
begin
  btNew:=TJSHTMLButtonElement(getHTMLElement('bt_new'));
  btNew.OnClick := @NewGame;
  FCanvas:=TJSHTMLCanvasElement(document.getElementById('my_canvas'));
  FCanvas.width:=window.innerWidth;
  FCanvas.height:=window.innerHeight;
  FCanvas.width:=BSIZE*4+GAP*5;
  FCanvas.height:=FCanvas.width;
  FCtx:=TJSCanvasRenderingContext2D(FCanvas.getContext('2d'));
  //Fctx.fillStyle:='#eeeeee';
  //Fctx.fillRect(0,0,window.innerWidth,window.innerHeight);
  FCtx.font:='bold 40px Arial';
  FCtx.textAlign:= 'center';
  document.onkeydown:=@OnFormKeyPress;
  BoardInit;
  DrawBoard;
end;

function TMyApplication.OnFormKeyPress(kTJSKeyBoardEvent): Boolean;
Var
  key word;
begin
  Result:=True;
  case K.Code of
    TJSKeyNames.ArrowRight key:=VK_RIGHT;
    TJSKeyNames.ArrowUp    key:=VK_UP;
    TJSKeyNames.ArrowLeft  key:=VK_LEFT;
    TJSKeyNames.ArrowDown  key:=VK_DOWN;
  end;
  k.preventDefault;
  if DoMove(keythen
    DrawBoard;
end;

function TMyApplication.NewGame(aEventTJSMouseEvent): boolean;
begin
  Shuffle;
  DrawBoard;
end;

procedure TMyApplication.DrawBoard;
var
  ixyInteger;
begin
  for i:=to CSIZE do begin
    FCtx.beginPath;
    x:=Board[i].x;
    x:=x*BSIZE+x*GAP+GAP;
    y:=Board[i].y;
    y:=y*BSIZE+y*GAP+GAP;
    FCtx.strokeStyle:='Black';
    if Board[i].then begin
      FCtx.fillStyle:=COLORBLANK;
      FCtx.rect(x,y,BSIZE,BSIZE);
      FCtx.fillRect(x,y,BSIZE,BSIZE);
      FCtx.stroke;
      Continue;
    end else begin
      if Board[i].n=i+then
        FCtx.fillStyle:=COLOROK
      else
        FCtx.fillStyle:=COLORWRONG;
      FCtx.rect(x,y,BSIZE,BSIZE);
      FCtx.fillRect(x,y,BSIZE,BSIZE);
      FCtx.fillStyle:='Black';
      FCtx.fillText(Board[i].n.ToStringBSIZE div 2y+BSIZE div 2);
      FCtx.stroke;
    end;
  end;
  //
end;


procedure TMyApplication.DoRun;
begin
  BindElements;
  BoardInit;
end;

var
  Application TMyApplication;

begin
  Application:=TMyApplication.Create(nil);
  Application.Initialize;
  Application.Run;
end.