unit mainformu;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DBClient, DB, SyncObjs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

procedure LoadTextFile(Filename: String);

var
  Form1: TForm1;
  AppDir: String;
  CDS: TClientDataSet;
  Event: TEvent;

implementation

uses TextFileProcessu;

{$R *.dfm}

var
  TextFileProcessor: TTextFileProcessor;


procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  TextFileProcessor.Terminate; //sets Terminated to True
  Event.SetEvent; //Trigger the event. Thread should be unblocked
  TextFileProcessor.WaitFor; //Just in case the thread was processing files, wait
  TextFileProcessor.Free;
  //Should be all done.
  CDS.Free;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  AppDir := ExtractFilePath(Application.ExeName);
  CDS := TClientDataSet.Create(nil);
  CDS.FileName := AppDir + 'HoldText.cds';
  if not FileExists(CDS.FileName) then
  begin
    CDS.FieldDefs.Add('Filename', ftString, 127, True);
    CDS.FieldDefs.Add('File', ftBlob);
    CDS.CreateDataSet;
    CDS.SaveToFile;
    CDS.Close;
  end;
  Event := TEvent.Create(nil, False, False, '');
  TextFileProcessor := TTextFileProcessor.Create(True);
  TextFileProcessor.Start;
end;

procedure LoadTextFile(Filename: String);
begin
  CDS.Open;
  CDS.LogChanges := False;
  try
    CDS.IndexFieldNames := 'Filename';
    if not CDS.FindKey([UpperCase(FileName)]) then
    begin
      CDS.Insert;
      CDS.Fields[0].AsString := UpperCase(FileName);
      TBlobField(CDS.Fields[1]).LoadFromFile(FileName);
    end
    else
    begin
      CDS.Edit;
      TBlobField(CDS.Fields[1]).LoadFromFile(FileName);
    end;
    CDS.Post;
  finally
    CDS.Close;
  end;
  DeleteFile(FileName)
end;

end.
