unit loadpuzu;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Grids, StdCtrls, Buttons;

type
  TLoadPuzzForm = class(TForm)
    sgPuzzle: TStringGrid;
    btnOK: TBitBtn;
    btnCancel: TBitBtn;
    procedure FormCreate(Sender: TObject);
    procedure sgPuzzleClick(Sender: TObject);
    procedure btnOKClick(Sender: TObject);
    procedure sgPuzzleDblClick(Sender: TObject);
  private
    { Private declarations }

  public
    { Public declarations }
    sFrom, sTo, sSol : String;
  end;

var
  LoadPuzzForm: TLoadPuzzForm;

implementation
USES IniFiles, ladSharU;

{$R *.DFM}
procedure TLoadPuzzForm.FormCreate(Sender: TObject);
VAR
  slTemp    : TStringList;
  N, R, Loc : Integer;
  S         : String;
begin
  slTemp := TStringList.Create;
  try
    WITH TIniFile.Create(ChangeFileExt(Application.ExeName, '.INI')) DO
      try
        ReadSectionValues('Puzzles', slTemp);
        slTemp.Sort;
        WITH sgPuzzle DO
          begin
            Cells[0,0] := 'From';
            Cells[1,0] := 'To';
            Cells[2,0] := 'Steps';
            Cells[3,0] := 'Solved?';
            R := 1;
            FOR N := 0 TO slTemp.Count-1 DO
              begin
                S := slTemp.Names[N];
                Loc := Pos('-', S);
                IF (Loc IN [4..8]) AND (Length(S)=(2*Loc)-1) THEN
                  begin
                    Cells[2, R] := IntToStr(length(slTemp.Values[S]) DIV 2);
                    Cells[0, R] := Copy(S, 1, Loc-1);
                    Cells[1, R] := Copy(S, Loc+1, Loc-1);
                    IF ReadBool('Solved', slTemp.Names[N], False) THEN
                      Cells[3, R] := 'Yes';
                    Inc(R);
                  end;
              end;
            RowCount := R;  
            sFrom := Cells[0, Row];
            sTo := Cells[1, Row];
          end;
      finally
        Free;
      end;
  finally
    slTemp.Free;
  end;
end;

procedure TLoadPuzzForm.sgPuzzleClick(Sender: TObject);
begin
  WITH Sender AS TStringGrid DO
    begin
      sFrom := Cells[0, Row];
      sTo := Cells[1, Row];
    end;
end;

procedure TLoadPuzzForm.sgPuzzleDblClick(Sender: TObject);
begin
  btnOKClick(btnOK);
end;

procedure TLoadPuzzForm.btnOKClick(Sender: TObject);
begin
  IF (sFrom='') OR (sTo='') THEN
    ModalResult := mrCancel
  ELSE
    begin
      WITH TIniFile.Create(IniName) DO
        try
          sSol := ReadString('Puzzles',
            Format('%s-%s', [sFrom, sTo]), '');
        finally
          Free;
        end;
      ModalResult := mrOK;
    end;
end;

end.
