unit MachSeqMon;

interface

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

type
  TMachSeqMonForm = class(TForm)
    List: TListView;
    Panel1: TPanel;
    btCreate: TBitBtn;
    btRemove: TBitBtn;
    btStart: TBitBtn;
    btStop: TBitBtn;
    btClose: TBitBtn;
    Timer: TTimer;
    ViewPanel: TPanel;
    listView: TListBox;
    btView: TBitBtn;
    btHelp: TBitBtn;
    procedure btCloseClick(Sender: TObject);
    procedure btCreateClick(Sender: TObject);
    procedure btRemoveClick(Sender: TObject);
    procedure TimerTimer(Sender: TObject);
    procedure btStartClick(Sender: TObject);
    procedure btStopClick(Sender: TObject);
    procedure btViewClick(Sender: TObject);
    procedure btHelpClick(Sender: TObject);
    procedure CreateActiveMachSeq(fname: string);
    procedure ExpandWindow(Sender: TObject);
    procedure listViewDrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
    procedure listViewDblClick(Sender: TObject);
  private
    function CheckBeforeStart: boolean;
  public
    function CanClose: boolean;
  end;

var
  MachSeqMonForm: TMachSeqMonForm;

implementation
uses
  MesConst, MachSeq, MachSeqCfg, MesLogging, Connecting, numbers, users, main;

{$R *.DFM}

procedure TMachSeqMonForm.btCloseClick(Sender: TObject);
begin
  if ViewPanel.Visible then begin
    ViewPanel.Visible := false;
    btCreate.Enabled := true;
    btRemove.Enabled := true;
    btView.Enabled := true;
    btStart.Enabled := true;
    btStop.Enabled := true;
  end else
    close;
end;

procedure TMachSeqMonForm.btCreateClick(Sender: TObject);
var
//  D: TMachSeq;
  MachSeqCfgForm: TMachSeqCfgForm;
begin
  MachSeqCfgForm := TMachSeqCfgForm.Create(Self);
  MachSeqCfgForm.ShowModal;
  if MachSeqCfgForm.MachSeqFile = '' then exit;

  CreateActiveMachSeq(MachSeqCfgForm.MachSeqFile);
end;

procedure TMachSeqMonForm.CreateActiveMachSeq(fname: string);
var
  D: TMachSeq;
begin
  if not FileExists(fname) then exit;
   
  with List.Items.Add do begin
    Data := nil;
    D := TMachSeq.Create(fname);
    D.List := List;
    if D.LoadSuccess then begin
      Data := pointer(D);
      Caption := D.Name;
      SubItems.Add(D.GetSeqStr);
      SubItems.Add(D.GetStateStr);
      SubItems.Add(fname);
      Selected := true;
    end else begin
      MessageDlg(D.s_err, mtError, [mbOk], 0);
      D.Free;
      Delete;
    end;
  end;
end;

procedure TMachSeqMonForm.btRemoveClick(Sender: TObject);
var
  D: TMachSeq;
begin
  if List.Selected <> nil then begin
    D := TMachSeq(List.Selected.Data);
    if D.State <> 0 then
      MessageDlg('Удалить можно только остановленный маршрут!', mtWarning, [mbOk], 0)
    else begin
      List.Selected.Delete;
      D.Free;
    end;
  end;
end;

procedure TMachSeqMonForm.TimerTimer(Sender: TObject);
var
  D: TMachSeq;
  i: integer;
  s: string;
begin
  if not rvgLogIn then exit;
  for i:=0 to List.Items.Count-1 do if List.Items[i].Data <> nil then begin
    D := TMachSeq(List.Items[i].Data);
    if D.State > 0 then D.Process;
    s := D.GetStateStr;
    if not(List.Items[i].SubItems[1] = s) then
      List.Items[i].SubItems[1] := s;
  end;
end;

procedure TMachSeqMonForm.btStartClick(Sender: TObject);
var
  D: TMachSeq;
begin
  if List.Selected = nil then exit;

  if UsersControlEnable then
    if not CheckAccess(PREVILEG_ZAPUSK_MARSH, true) then exit;

  D := TMachSeq(List.Selected.Data);

  if D.State in [6..8] then begin
    MessageDlg('Выполняется останов маршрута. Запуск невозможен!', mtWarning, [mbOk], 0);
    exit;
  end;

  if MessageDlg('Запустить маршрут?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin
    if CheckBeforeStart then begin
      D.StartStateCnt := iif(D.State=255, D.StateCnt, 0);
      D.StateCnt := 0;
      D.State := 1;
      SaveMessageText(mcMStart_text, D.Name, '', mcMStart_bc, mcMStart_fc);
    end;
  end;
end;

function TMachSeqMonForm.CheckBeforeStart: boolean;
var
  i,j,k: integer;
  D,Q: TMachSeq;
  s, d_machs: string;
begin
  D := TMachSeq(List.Selected.Data);

  d_machs := ';';
  for j:=0 to D.ItemCount-1 do
    if D.Items[j].ItemType = siMACH then
        d_machs := d_machs + PMachSeqRec(D.Items[j].Item)^.TagName + ';';

  for i:=0 to List.Items.Count-1 do
    if not List.Items[i].Selected then begin
      Q := TMachSeq(List.Items[i].Data);
      if Q.State>0 then
        for j:=0 to Q.ItemCount-1 do
          if Q.Items[j].ItemType = siMACH then begin
            s := ';'+PMachSeqRec(Q.Items[j].Item)^.TagName+';';

            if pos(s, D.SharedMachs) > 0 then continue;

            if pos(s, d_machs) > 0 then begin
              ShowMessage('Данный маршрут запустить нельзя, т.к. уже запущен маршрут "' +
                    List.Items[i].Caption + '", ' + 'который использует тоже оборудование, ' +
                    'что и запускаемый (машина ' + PMachSeqRec(Q.Items[j].Item)^.TagName + ')!');
              result:=false;
              exit;
            end;
          end;
    end;

  result:=true;
end;

procedure TMachSeqMonForm.btStopClick(Sender: TObject);
var
  D: TMachSeq;
begin
  if List.Selected = nil then exit;

  if UsersControlEnable then
    if not CheckAccess(PREVILEG_ZAPUSK_MARSH, true) then exit;

  D := TMachSeq(List.Selected.Data);
  if D.State = 0 then exit;
  if MessageDlg('Остановить маршрут?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin
    D.State := 6;
    SaveMessageText(mcMStop_text, D.Name, '', mcMStop_bc, mcMStop_fc);
  end;
end;

procedure TMachSeqMonForm.btViewClick(Sender: TObject);
var
  F: TextFile;
  s: string;
begin
  if List.Selected = nil then exit;
  ViewPanel.Visible := true;
  btCreate.Enabled := false;
  btRemove.Enabled := false;
  btView.Enabled := false;
  btStart.Enabled := false;
  btStop.Enabled := false;

  if ViewPanel.Visible then begin
    ViewPanel.Align := alClient;
    listView.Clear;
//    listView.Items.Add(List.Selected.Subitems[2]);
//    listView.Items.Add('');
    AssignFile(F, List.Selected.Subitems[2]);
    Reset(F);
    while not(eof(F)) do begin
      readln(F, s);
      listView.Items.Add(s);
    end;
    CloseFile(F);
  end;
end;

procedure TMachSeqMonForm.btHelpClick(Sender: TObject);
begin
//  ShowCommonHelp('msq0.htm');
end;

function TMachSeqMonForm.CanClose: boolean;
var
  i: integer;
//  D: TMachSeq;
begin
  result := true;
  for i:=0 to List.Items.Count-1 do
    with TMachSeq(List.Items[i].Data) as TMachSeq do
      if State <> 0 then
        result := false;
end;

procedure TMachSeqMonForm.ExpandWindow(Sender: TObject);
var
  x: integer;
begin
  if tag = 0 then begin
    tag := 1;
    Width := Width + Left;
    Left := Left div 2;
    Height := Height + Top;
    Top := Top div 2;
  end else begin
    tag := 0;
    Left := Left * 2;
    Width := Width - Left;
    Top := Top * 2;
    Height := Height - Top;
  end;
end;

procedure TMachSeqMonForm.listViewDrawItem(Control: TWinControl;
  Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
  s: string;
begin
  s := trim(listView.Items[index]) + ' ';

  if copy(s,1,3)='///' then begin
    listView.Canvas.Brush.Color := clAqua;
    listView.Canvas.Font.Color := clBlack;
    listView.Canvas.Font.Style := [];
    listView.Canvas.Font.Name := 'Time New Roman'
  end else
  if copy(s,1,2)='//' then begin
    listView.Canvas.Brush.Color := listView.Color;
    listView.Canvas.Font.Color := clNavy;
    listView.Canvas.Font.Style := [fsItalic];
    listView.Canvas.Font.Name := 'Time New Roman'
  end else
  if uppercase(copy(s,1,7))='.SHARED' then begin
    listView.Canvas.Brush.Color := listView.Color;
    listView.Canvas.Font.Color := clGrayText;
    listView.Canvas.Font.Style := [];
    listView.Canvas.Font.Name := 'Courier New'
  end else
  if s[1] in ['0'..'9','['] then begin
    listView.Canvas.Brush.Color := listView.Color;
    listView.Canvas.Font.Color := clBlack;
    listView.Canvas.Font.Style := [fsBold];
    listView.Canvas.Font.Name := 'Courier New'
  end else begin
    listView.Canvas.Brush.Color := listView.Color;
    listView.Canvas.Font.Color := clBlack;
    listView.Canvas.Font.Style := [];
    listView.Canvas.Font.Name := 'Courier New'
  end;

  if index=0 then begin
    listView.Canvas.Brush.Color := listView.Color;
    listView.Canvas.Font.Color := clRed;
    listView.Canvas.Font.Style := [fsBold];
//    listView.Canvas.Font.Size := 12;
    listView.Canvas.Font.Name := 'Time New Roman'
  end;

  listView.Canvas.FillRect(Rect);
  listView.Canvas.TextOut(Rect.Left + 2, Rect.Top, listView.Items[Index]);

end;

procedure TMachSeqMonForm.listViewDblClick(Sender: TObject);
var
  s,ss: string;
  F: TextFile;
begin
  if listView.ItemIndex<0 then exit;
  s := trim(listView.Items[listView.ItemIndex]);

  if copy(s,1,1) = '[' then begin
    ss := uppercase(copy(s,2,length(s)-2));
    listView.Clear;
    listView.Items.Add('#GROUP ' + ss);
    AssignFile(F, CurDir + 'MachSeq\'+MachSeq_GroupsFile);
    try
      reset(F);
      if FindMsqGroup(F,ss) then
        while not(eof(F)) do begin
          readln(F, s);
          s := trim(s);
          if copy(s,1,1)='#' then break;
          if (s='') or (copy(s,1,2)='//') then continue;
          listView.Items.Add(s);
        end
      else
        listView.Items.Add('Подгруппа ' + ss + ' не найдена!');
    except
    end;
    CloseFile(F);

  end;
end;

end.
