unit main;

interface

uses
  SysUtils, Types, Classes, Variants, QGraphics, QControls, QForms, QDialogs,
  QStdCtrls, QExtCtrls, RARegAuto, IniFiles, RAI2;

type
  TMainForm = class(TForm)
    Panel1: TPanel;
    Panel2: TPanel;
    Memo1: TMemo;
    Memo2: TMemo;
    Panel3: TPanel;
    Run: TButton;
    RAI2Program1: TRAI2Program;
    pnlResult: TPanel;
    Panel4: TPanel;
    SampleSelector: TComboBox;
    pnlTime: TPanel;
    Label1: TLabel;
    RegAuto1: TRegAuto;
    RegAuto2: TRegAuto;
    procedure RunClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure SampleSelectorSelect(Sender: TObject);
    procedure RAI2Program1GetValue(Sender: TObject; Identifer: String;
      var Value: Variant; Args: TArgs; var Done: Boolean);
    procedure RegAuto1AfterSave(Sender: TObject);
    procedure RegAuto1AfterLoad(Sender: TObject);
  private
    { Private declarations }
    InternalExamplesCount: Integer;
    //CurFileName: TFileName;
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

uses
    RAI2_RAI2
  , RAI2_System
  , RAI2_Types
  , RAI2_SysUtils
  , RAI2_Classes
  , RAI2_Contnrs
  , RAI2_Graphics
  , RAI2_Controls
  , RAI2_Dialogs
  , RAI2_Forms
  ;

{$R *.xfm}

procedure TMainForm.RunClick(Sender: TObject);
const
  Bool : array [boolean] of string = ('False', 'True');
var
  T1: TDateTime;
begin
  RAI2Program1.Source := Memo1.Lines.Text;

  pnlResult.Caption := 'Working';
  pnlResult.Color := clRed;
  pnlResult.Update;
  T1 := Now;      

  try try
    if Sender = Run then
      RAI2Program1.Run;
    {else if Sender = Compile  then
      RAI2Program1.Compile;}

  pnlTime.Caption := FormatDateTime('HH:mm:ss.zzz', Now - T1);

	case VarType(RAI2Program1.VResult) of
		varBoolean:
			pnlResult.Caption := Bool[boolean(RAI2Program1.VResult)];
		varString, varInteger, varDouble :
			pnlResult.Caption := RAI2Program1.VResult;
		varEmpty:
			pnlResult.Caption := 'Empty';
		varNull:
			pnlResult.Caption := 'Null';
    varObject:
      if V2O(RAI2Program1.VResult) = nil then
  			pnlResult.Caption := 'Object: nil'
      else
  			pnlResult.Caption := 'Object: ' + V2O(RAI2Program1.VResult).ClassName;
		varSet:
			pnlResult.Caption := 'Set: ' + IntToStr(V2S(RAI2Program1.VResult));
		else
			pnlResult.Caption := '!Unknown!';
	end;
  except
    on E : ERAI2Error do
    begin
      pnlResult.Caption := IntToStr(E.ErrCode) + ': ' + StringReplace(E.Message, #10, ' ', []);
      if E.ErrPos > -1 then
      begin
        Memo1.SelStart := E.ErrPos;
        Memo1.SelLength := 0;
      end;
      Memo1.SetFocus;
    end;
    on E : Exception do
    begin
      pnlResult.Caption := IntToStr(RAI2Program1.LastError.ErrCode) + ': ' +
        StringReplace(RAI2Program1.LastError.Message, #10, ' ', []);
      if RAI2Program1.LastError.ErrPos > -1 then
      begin
        Memo1.SelStart := RAI2Program1.LastError.ErrPos;
        Memo1.SelLength := 0;
      end;
      Memo1.SetFocus;
      raise;
    end
    else
    begin
      pnlResult.Caption := 'error';
      raise;
    end;
  end;
  finally
    pnlResult.Color := clBtnFace;
  end;
end;

procedure TMainForm.FormCreate(Sender: TObject);
var
  SearchRec : TSearchRec;
  DosError  : integer;
begin
  try
    RegAuto2.IniStrings.LoadFromFile(ChangeFileExt(ParamStr(0), '.ini'));
  except
    MessageDlg('Can''t load file "rai2test.ini".'#13+
      'Please put it in same folder as rai2test executable.',
      mtError, [mbCancel], -1);
  end;
  RegAuto2.ReadSection('Demos', SampleSelector.Items);

  InternalExamplesCount := SampleSelector.Items.Count;

  DosError := FindFirst(ExtractFilePath(ParamStr(0)) + 'samples/*.pas', faAnyFile, SearchRec);
  while DosError = 0 do begin
    if not ((SearchRec.Attr and faDirectory) = faDirectory)  then
    begin
      if (SampleSelector.Items.IndexOf('------ custom files (samples folder) ------') = -1) then
        SampleSelector.Items.Add('------ custom files (samples folder) ------');
      SampleSelector.Items.Add(ChangeFileExt(SearchRec.Name, ''));
    end;
    DosError := FindNext(SearchRec);
  end;
  FindClose(SearchRec);
end;

procedure TMainForm.RegAuto1AfterSave(Sender: TObject);
begin
  RegAuto1.WriteString(Name, 'sample', SampleSelector.Text);
end;

procedure TMainForm.RegAuto1AfterLoad(Sender: TObject);
var
  sample: string;
begin
  sample := RegAuto1.ReadString(Name, 'sample', '');
  if (sample <> '') then
    SampleSelector.ItemIndex := SampleSelector.Items.IndexOf(sample)
  else
    SampleSelector.ItemIndex := 0;
  SampleSelectorSelect(nil);
end;

procedure TMainForm.SampleSelectorSelect(Sender: TObject);
var
  Sample: string;
begin
  Memo1.Lines.Clear;
  Memo2.Lines.Clear;
  if SampleSelector.ItemIndex < InternalExamplesCount then
  begin
    Sample := SampleSelector.Text;
    if Pos('<Not yet implemented> - ', Sample) > 0 then
      Sample := Copy(Sample, Length('<Not yet implemented> - ') + 1, 1000);

    RegAuto2.ReadWholeSection(Sample + '\Source', Memo1.Lines);
    RegAuto2.ReadWholeSection(Sample + '\Description', Memo2.Lines);
    //Notebook1.ActivePage := RegAuto2.ReadString(SampleSelector.Text, 'Page', 'Default');
  end else
  if SampleSelector.ItemIndex = InternalExamplesCount then
  begin
    Memo1.Text := 'Please, select an example';
    Memo2.Text := 'Please, select an example';
  end
  else
  begin
    Memo1.Lines.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'samples/' + SampleSelector.Text + '.pas');
    //Notebook1.ActivePage := 'Default';
  end;
  Memo1.SelStart := 0;
  Memo2.SelStart := 0;
//  Memo1.Refresh;
end;
 procedure TMainForm.RAI2Program1GetValue(Sender: TObject;
  Identifer: String; var Value: Variant; Args: TArgs; var Done: Boolean);
begin
  if Cmp(Identifer, 'Test') then
  begin
    Done := True;
    Value := O2V(Self);
  end
  else
  if Cmp(Identifer, 'ShowMessage') and (Args.Obj = Self) then
  begin
    Done := True;
    ShowMessage(VarToStr(Args.Values[0]));
    Value := Null;
  end
  else
  if Cmp(Identifer, 'MyFunction') then
  begin
    Done := True;
    Value := Args.Values[0] + 1;
  end
end;

initialization
  RAI2_System.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Types.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_SysUtils.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Classes.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Contnrs.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Graphics.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Controls.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Dialogs.RegisterRAI2Adapter(GlobalRAI2Adapter);
  RAI2_Forms.RegisterRAI2Adapter(GlobalRAI2Adapter);
end.
