unit DeviceList;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ActnList;

type
  TDeviceListForm = class(TForm)
    ListBox1: TListBox;
    bOk: TButton;
    bCancel: TButton;
    ActionList1: TActionList;
    acRefresh: TAction;
    acOk: TAction;
    procedure FormCreate(Sender: TObject);
    procedure ListBox1DblClick(Sender: TObject);
    procedure acRefreshExecute(Sender: TObject);
    procedure acOkExecute(Sender: TObject);
    procedure acOkUpdate(Sender: TObject);
    procedure FormActivate(Sender: TObject);
  private
    { Private declarations }
    isCreation : boolean;
  public
    { Public declarations }
  end;

var
  DeviceListForm: TDeviceListForm;

implementation

uses
  Modules, Main, Osc_DLL, Config;

{$R *.dfm}

procedure TDeviceListForm.FormCreate(Sender: TObject);
begin
  isCreation := true;
end;

procedure TDeviceListForm.ListBox1DblClick(Sender: TObject);
begin
  if ListBox1.ItemIndex > -1 then
     bOk.Click;
end;

procedure TDeviceListForm.acRefreshExecute(Sender: TObject);
var
  P    : PChar;
  i, j : integer;
  List : TStringList;
begin
  acOk.Enabled := false;

  ListBox1.ItemIndex := -1;
  ListBox1.Items.BeginUpdate;
  Screen.Cursor := crHourGlass;
  try
    ListBox1.Items.Clear;
    for i := 0 to ModuleList.Count - 1 do
    begin
      if Assigned(@ModuleList.Items[i].DiveceList) then
      begin
        List := TStringList.Create;
        try
          ModuleList.Items[i].DiveceList(P);
          List.SetText(P);
          for j := 0 to List.Count - 1 do
              ListBox1.Items.AddObject(List.Strings[j], ModuleList.Items[i]);
        finally
          List.Free;
        end;
      end;
    end;
  finally
    Screen.Cursor := crDefault;
    ListBox1.Items.EndUpdate;
  end;

  if ListBox1.Items.Count > 0 then
      ListBox1.ItemIndex := 0;
end;

procedure TDeviceListForm.acOkExecute(Sender: TObject);
begin
  if ListBox1.ItemIndex > -1 then
  begin
    ModuleList.ActiveModule := TModule(ListBox1.Items.Objects[ListBox1.ItemIndex]);
    if not ModuleList.ActiveModule.ConnectTo(PChar(ListBox1.Items.Strings[ListBox1.ItemIndex])) then
    begin
      ModalResult := mrNone;
      ModuleList.ActiveModule := nil;
      Configuration.MainItem.DeviceName := '';
      MainForm.Connected := false;
      MessageBox(handle, 'Нет соединения с устройством.', nil, MB_OK or MB_ICONSTOP);
    end
    else
    begin
      Configuration.MainItem.DeviceName := ListBox1.Items.Strings[ListBox1.ItemIndex];
      MainForm.Connected := true;
    end;
  end;
end;

procedure TDeviceListForm.acOkUpdate(Sender: TObject);
begin
  TAction(Sender).Enabled := ListBox1.ItemIndex > -1;
end;

procedure TDeviceListForm.FormActivate(Sender: TObject);
begin
  if isCreation then
  begin
    try
      Update;
      acRefresh.Execute;
    finally
      isCreation := false;
    end;
  end;
end;

end.
