unit Connecting;

interface
Uses
  windows,
  Dialogs, SysUtils, pFIBDatabase;

  procedure ConnectSystem;
  procedure DisconnectSystem;

  function ConnectToTagLogging: boolean;
  function ConnectToDataClient: boolean;

  procedure DisconnectFromTagLogging;
  procedure DisconnectFromDataClient;

  function checkDataClientConnection: boolean;
  procedure checkTagloggingConnection;
  procedure checkMesloggingConnection;

  procedure StartDataClientReconnecter;

  function isTagloggingConnected: boolean;
  function isMesloggingConnected: boolean;

implementation
uses
  infodlg,
  _PrjProcs,
  DataClientConnectBad,
  CriticalAlerts,
  inifiles,
  main,
  Status,
  TagStorage,
  DataMod,
  MesLogging,
  users,
  classes,
  rpTcpClientGlobals,
  RpVisualUtils,
  RpVisualGlobal,
  RpVisualMain,
  DataClientBase;


//============================================================================
// ВХОД                                                              LOGIN
//============================================================================
procedure ConnectSystem;
begin
  rvgLogIn := false;
  rvgPrjOnTimerEnabled := false;
  Form1.ScreenTimer.Enabled := false;
  _PrjBeforeStart;


  if not ConnectToDataClient then begin
    StartDataClientReconnecter;
    exit;
  end;

  if not ConnectToTagLogging then begin
    showInfoDlg('Ошибка подключения к базе данных архивов значений!', mtError, [mbOk], 0);
  end;

  if not ConnectToMesLogging then begin
    showInfoDlg('Ошибка подключения к базе данных сообщений!', mtError, [mbOk], 0);
  end;

  initCriticalAlerts;

  if not LoginUser then begin
    DisconnectSystem;
    exit;
  end;

  rvgLogIn := true;

  _PrjAfterStart;

  rvgPrjOnTimerEnabled := true;
  Form1.ScreenTimer.Enabled := true;

  ScanScadaObjects(dsmAll, InitDeviceProc);

  updateMainFormButtons;
  _PageControlChange(nil);
end;


procedure DisconnectSystem;
begin
  _PrjBeforeStop;

  rvgLogIn := false;
  rvgPrjOnTimerEnabled := false;
  Form1.ScreenTimer.Enabled := false;

  DisconnectFromMesLogging;
  DisconnectFromTagLogging;
  DisconnectFromDataClient;

  _PrjAfterStop;
  closeCriticalAlerts;
  updateMainFormButtons;
end;



function ConnectToDataClient: boolean;
begin
  ShowStatusMessage('Подключение к серверу данных');

  initDataClient;
  DataClient.Start;

  if DataClient.getPortConnectBad = 0 then begin
    result := true;
  end else begin
    result := false;
    DataClient.Stop;
  end;

  CloseStatusMessage;
end;


procedure DisconnectFromDataClient;
begin
  DataClient.Stop;
end;



function ConnectToTagLogging: boolean;
begin
  result := true;
  if databaseDisabled then Exit;

  ShowStatusMessage('Подключение к БД архивов значений');

  dm.pFIBDbArc.DatabaseName := DBNameTag;
  dm.pFIBDbArc.ConnectParams.UserName := DBUser;
  dm.pFIBDbArc.ConnectParams.Password := DBPass;
  try
    dm.QueryArc.Transaction.Active := false;
    dm.pFIBDbArc.Connected := true;
  except
    result := false;
  end;

  CloseStatusMessage;
end;


procedure DisconnectFromTagLogging;
begin
  if databaseDisabled then Exit;
  try
    dm.pFIBDbArc.Connected := false;
  except
  end;  
end;


procedure StartDataClientReconnecter;
begin
  if DataClientConnectBadForm = nil then begin
    DataClientConnectBadForm := TDataClientConnectBadForm.Create(form1);
    DataClientConnectBadForm.Show;
    Form1.ConnectButton.Enabled := false;
  end;
end;


function checkDataClientConnection: boolean;
begin
  result := true;
  if (DataClient.PortConnectBad=1) then begin
    DisconnectSystem;
    StartDataClientReconnecter;
    result := false;
  end;
end;


procedure checkTagloggingConnection;
//var
//  t: Cardinal;
//  res: boolean;
begin
  if databaseDisabled then exit;
  try
    if not dm.pFIBDbArc.Connected then
      exit;

//    t := GetTickCount;
//    res := dm.pFIBDbArc.ExTestConnected(laCloseConnect);
//    t := GetTickCount - t;
//    Form1.lbTime.Caption := IntToStr(t);
//    if not res then begin

    if not dm.pFIBDbArc.ExTestConnected(laCloseConnect) then begin
      ShowMessage('Связь с базой данных архивов значений потеряна!');
      updateMainFormButtons;
      try
        dm.pFIBDbArc.Connected := false;
      except
      end;
    end;
  except
  end;
end;


procedure checkMesloggingConnection;
begin
  if databaseDisabled then exit;
  try
    if not dm.pFIBDbMes.Connected then exit;
    if not dm.pFIBDbMes.ExTestConnected(laCloseConnect) then begin
      ShowMessage('Связь с базой данных сообщений потеряна!');
      updateMainFormButtons;
      ClearMesBar;
      try
        dm.pFIBDbMes.Connected := false;
      except
      end;
    end;
  except
  end;
end;


function isTagloggingConnected: boolean;
begin
  try
    result := (not databaseDisabled) and (dm.pFIBDbArc.Connected);
  except
    result := False;
  end;
end;

function isMesloggingConnected: boolean;
begin
  try
    result := (not databaseDisabled) and (dm.pFIBDbMes.Connected);
  except
    result := False;
  end;
end;


end.
