unit MainFrm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, ComCtrls, StdCtrls, SUPassStorage, SUGeneral;

type
  TfmMain = class(TForm)
    lvRecords: TListView;
    Panel1: TPanel;
    bbOpen: TButton;
    bbSave: TButton;
    bbAdd: TButton;
    bbDelete: TButton;
    OpenDialog: TOpenDialog;
    SaveDialog: TSaveDialog;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure bbOpenClick(Sender: TObject);
    procedure bbSaveClick(Sender: TObject);
    procedure bbAddClick(Sender: TObject);
    procedure bbDeleteClick(Sender: TObject);
  private
    { Private declarations }
    FStorage: TSUPassStorage;

    procedure Refresh;
  public
    { Public declarations }
  end;

var
  fmMain: TfmMain;

implementation

uses NewPassFrm;

{$R *.dfm}

procedure TfmMain.FormCreate(Sender: TObject);
begin
  FStorage := TSUPassStorage.Create(nil);
end;

procedure TfmMain.FormDestroy(Sender: TObject);
begin
  FreeAndNil(FStorage);
end;

procedure TfmMain.bbOpenClick(Sender: TObject);
var
  Password: string;
begin
  if not OpenDialog.Execute then
    Exit;
  if not InputQuery('Password', 'Enter a password (may be blank):', Password) then
    Exit;

  FStorage.Clear;
  FStorage.LoadFromFile(OpenDialog.FileName, Password);
  Refresh;
end;

procedure TfmMain.bbSaveClick(Sender: TObject);
var
  Password: string;
begin
  if not SaveDialog.Execute then
    Exit;
  if not InputQuery('Password', 'Enter a password (may be blank):', Password) then
    Exit;

  FStorage.SaveToFile(SaveDialog.FileName, Password);
end;

procedure TfmMain.Refresh;
var
  Li: TListItem;
  i: integer;
begin
  lvRecords.Items.BeginUpdate;
  try
    lvRecords.Items.Clear;

    for i := 0 to FStorage.Count - 1 do
    begin
      Li := lvRecords.Items.Add;
      Li.Caption := FStorage[i].Title;
      Li.SubItems.Add(FStorage[i].Username);
      Li.SubItems.Add(FStorage[i].Password);
      Li.SubItems.Add(FStorage[i].URL);
      Li.SubItems.Add(FStorage[i].Note);
    end;
  finally
    lvRecords.Items.EndUpdate;
  end;
end;

procedure TfmMain.bbAddClick(Sender: TObject);
var
  fmNewRecord: TfmNewRecord;
begin
  fmNewRecord := TfmNewRecord.Create(nil);
  try
    if fmNewRecord.ShowModal <> mrOk then
      Exit;

    FStorage.Add(fmNewRecord.edTitle.Text, fmNewRecord.edUsername.Text,
      fmNewRecord.edPassword.Text, fmNewRecord.edURL.Text,
      fmNewRecord.edNote.Text);

    Refresh;
  finally
    fmNewRecord.Free;
  end;
end;

procedure TfmMain.bbDeleteClick(Sender: TObject);
begin
  if lvRecords.ItemIndex >= 0 then
  begin
    FStorage.Delete(lvRecords.ItemIndex);
    Refresh;
  end;
end;

end.
