unit SetChannel;

interface

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

type
  TSetChannelForm = class(TForm)
    GroupBox1: TGroupBox;
    OkButton: TButton;
    CancelButton: TButton;
    Label1: TLabel;
    AddressEdit: TEdit;
    AddressUpDown: TUpDown;
    Label2: TLabel;
    NumEdit: TEdit;
    NumUpDown: TUpDown;
    cbFreq: TCheckBox;
    procedure FormActivate(Sender: TObject);
    procedure CancelButtonClick(Sender: TObject);
    procedure OkButtonClick(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
  private
    { Private declarations }
  public
    { Public declarations }
    Channel: integer;
    DeviceName: string;
  end;

procedure SetChannelExecute(tagid: integer; devicename: string);

var
  SetChannelForm: TSetChannelForm = nil;

implementation
uses
  UserControlEx,
  MesConst,
  TagStorage,
  MesLogging,
  numbers,
  users,
  RpVisualUtils,
  RpVisualMain;

{$R *.DFM}


procedure SetChannelExecute(tagid: integer; devicename: string);
var
  win_exist: boolean;
begin
  win_exist := SetChannelForm <> nil;
  if not win_exist then
    SetChannelForm := TSetChannelForm.Create(nil);

  SetChannelForm.Channel := GetTagValue(tagid);
  SetChannelForm.DeviceName := DeviceName;
  if SetChannelForm.ShowModal = mrOk then begin
    SaveMessageText(mcSetChannel_text, DeviceName, GetStringChannelName(SetChannelForm.Channel), mcSetChannel_bc, mcSetChannel_fc );
    SetTagValue( tagid, SetChannelForm.Channel );
  end;

  if not win_exist then
    FreeAndNil(SetChannelForm);
end;

procedure TSetChannelForm.FormActivate(Sender: TObject);
begin
  AddressUpDown.Position := Channel shr 8;
  NumUpDown.Position := Channel and $7F;
  cbFreq.Checked := (Channel and $80) > 0;
  AddressEdit.SetFocus;
  AddressEdit.SelectAll;

end;

procedure TSetChannelForm.CancelButtonClick(Sender: TObject);
begin
  close;
end;

procedure TSetChannelForm.OkButtonClick(Sender: TObject);
begin
  if isModeUserEx then begin
//    if not isPermitted(ClassName + '~Установка адреса') then
//      exit;
  end else
    if not CheckAccess(PREVILEG_CHANNELS, true) then
      exit;

  Channel := (AddressUpDown.Position shl 8) + NumUpDown.Position + iif(cbFreq.Checked, $80, 0);

  _WritelnAdminLog('Установка канала: ' + DeviceName + ' = ' + AddressEdit.Text + '-' + NumEdit.Text +
      iif(cbFreq.Checked, ' A', ''));


  ModalResult := mrOk;
end;

procedure TSetChannelForm.FormKeyPress(Sender: TObject; var Key: Char);
begin

  if key in ['.', '+'] then begin

    if AddressEdit.Focused then
      NumEdit.SetFocus
    else
      if NumEdit.Focused then
        AddressEdit.SetFocus;

    key:=#0;
  end;


  if key in ['*', '-'] then begin
    cbFreq.Checked := not cbFreq.Checked;
    key := #0;
  end;
end;

end.
