unit CriticalAlertSetup;

interface

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

type
  TCriticalAlertSetupForm = class(TForm)
    Label17: TLabel;
    list: TListView;
    btAdd: TButton;
    btDel: TButton;
    btSave: TBitBtn;
    procedure btSaveClick(Sender: TObject);
    procedure btAddClick(Sender: TObject);
    procedure btDelClick(Sender: TObject);
  private
    procedure SaveToIni;
    { Private declarations }
  public
    procedure LoadFromIni;
  end;

var
  CriticalAlertSetupForm: TCriticalAlertSetupForm;

implementation
uses
  criticalalertprop,
  CriticalAlerts,
  RpVisualGlobal,
  inifiles;


{$R *.dfm}

procedure TCriticalAlertSetupForm.LoadFromIni;
var
  l: TStringList;
  i,k,alerts_cnt: integer;
  s: string;
begin
  l := TStringList.Create;
  with TIniFile.Create(CurDir + RpVisualIniFile) do try
    ReadSection('CriticalAlerts', l);
    alerts_cnt := l.Count;

    for i:=0 to alerts_cnt - 1 do
      with list.items.add do begin
      s := ReadString('CriticalAlerts', l[i], '');

      k := Pos('=', s);
      subitems.Add( Copy(s, 1, k-1) );
      System.Delete(s, 1, k);

      k := Pos(';', s);
      subitems.Add( Copy(s, 1, k-1) );

      caption := Copy(s, k+1, Length(s)-k+1);

    end;

  finally
    Free;
  end;
  l.Free;
end;


procedure TCriticalAlertSetupForm.SaveToIni;
var
  i: integer;
begin
  with TIniFile.Create(CurDir + RpVisualIniFile) do try
    EraseSection('CriticalAlerts');
    for i:=0 to list.Items.Count-1 do
      WriteString('CriticalAlerts', 'Alert' + IntToStr(i),
            list.Items[i].SubItems[0] + '=' + list.Items[i].SubItems[1] + ';' + list.Items[i].Caption);

    ShowMessage('Сохранение критических сообщений выполнено!');
  finally
    Free;
  end;

end;


procedure TCriticalAlertSetupForm.btSaveClick(Sender: TObject);
begin
  SaveToIni;
end;

procedure TCriticalAlertSetupForm.btAddClick(Sender: TObject);
var
  edit_mode: boolean;
begin
  edit_mode := sender = list;
  if (edit_mode) and (list.Selected=nil) then exit;

  with TCriticalAlertPropForm.Create(self) do try
    if edit_mode then begin
      edMessage.Text := list.Selected.Caption;
      edTagname.Text := list.Selected.SubItems[0];
      edValue.Text := list.Selected.SubItems[1];
    end;

    if ShowModal=mrOk then begin
      if not edit_mode then begin
        list.Selected := list.Items.Add;
        list.Selected.SubItems.Add('');
        list.Selected.SubItems.Add('');
      end;

      with list.Selected do begin
        list.Selected.Caption := edMessage.Text;
        list.Selected.SubItems[0] := edTagname.Text;
        list.Selected.SubItems[1] := edValue.Text;
      end;

    end;
  finally
    free;
  end;
end;

procedure TCriticalAlertSetupForm.btDelClick(Sender: TObject);
begin
  if (list.Selected=nil) then exit;
  list.Selected.Delete;
end;

end.
