unit ShowLastWesRec;

interface
uses
  Types,
  Graphics,
  StdCtrls,
  SysUtils,
  Classes,
  Dialogs,
  ExtCtrls,
  Controls,
  ScadaBase,
  Forms,
  FIBQuery, pFIBQuery, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet
  ;

const
  dt_format = 'yyyy.mm.dd hh:nn:ss';
  dataformat = 'yyyymmdd';
  debug_mode = false;

type



  TShowLastWesRec = class( TCustomScadaObject )
  public


    url        : string;
    user, pass : string;
    Connected  : boolean;


    WES        : TpFIBDatabase;
    Trans      : TpFIBTransaction;
    qry        : TpFIBQuery;

    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Connect;
    procedure Disconnect;

    function GetRec (S:string; var W :int64; var N : int64; var t1 : string; var t2 : string ) : integer;

    procedure ExceptionClose;
    function  IsConnected : boolean;

    procedure Init; override;
    procedure Process; override;

  end;




function createShowLastWesRec(var parent: TPanel; DBLink, DBuser, DBpass : string): TShowLastWesRec;

implementation
uses
  RpVisualGlobal,
  TagStorage,
  Variants,
  HyperStr;

procedure Log(s: string);
var
  F: TextFile;
begin
  try
    AssignFile(F, CurDir + 'error.log');
    if not FileExists(CurDir + 'error.log') then
      rewrite(F)
    else begin
      append(F);
    end;

    Writeln(F, DateTimeToStr(now) + ': ' + s);
  finally
    try
      CloseFile(F);
    except
    end;
  end;
end;


function createShowLastWesRec(var parent: TPanel; DBLink, DBuser, DBpass : string): TShowLastWesRec;
var  ShowerLastRec : TShowLastWesRec;
begin
  ShowerLastRec := TShowLastWesRec.Create(parent);
  ShowerLastRec.parent := parent;
  ShowerLastRec.url  := DBLink;
  ShowerLastRec.user := DBUser;
  ShowerLastRec.pass := DBPass;

  result := ShowerLastRec;
end;


function  TShowLastWesRec.IsConnected : boolean;
begin
 result := Connected AND WES.Connected;
end;


constructor TShowLastWesRec.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  Connected := false;

  WES        := TpFIBDatabase.Create(AOwner);
  Trans      := TpFIBTransaction.Create(AOwner);
  qry        := TpFIBQuery.Create(AOwner);

end;






destructor TShowLastWesRec.Destroy;
begin
  WES.Destroy;
  Trans.Destroy;
  qry.Destroy;

  inherited Destroy;

end;


procedure TShowLastWesRec.Process;
begin
  inherited;
  if not rvgLogIn then Exit;
end;


procedure TShowLastWesRec.ExceptionClose;
begin
 if Qry.Transaction.Active then
   begin
     Qry.Transaction.Rollback;
     qry.Close;
     qry.FreeHandle;
   end;
end;


procedure TShowLastWesRec.Init;
begin
  inherited;
end;


function TShowLastWesRec.GetRec (S:string; var W :int64; var N : int64; var t1 : string; var t2 : string ) : integer;
var sql:string;
    SavedToDB:boolean;
    c : integer;
begin
  if NOT IsConnected then
    begin
      result := -1;
      exit;
    end;

  SavedToDB:=false;
  sql:='SELECT FIRST 1 IDM FROM MODULES WHERE NAME LIKE '''+S+''' ';
  sql := 'SELECT FIRST 1 WES, WNUM, DTBEG, DTEND FROM STATUS WHERE IDM IN (' + sql + ') ORDER BY DTEND desc';

 try
   ExceptionClose;

   qry.SQL.text:=sql;

   qry.Transaction.StartTransaction;
   qry.ExecQuery;

   c:=0;

   if qry.Eof then begin
     c := 0;
     w := 0;
     n := 0;
   end else begin
     c := c + 1;
     w := qry.Fields[0].AsInt64;
     n := qry.Fields[1].AsInt64;
     t1 := qry.Fields[2].AsString;
     t2 := qry.Fields[3].AsString;
   end;

   Qry.Transaction.Commit;
   qry.Close;
   qry.FreeHandle;
   result := c;

 except
   log (DateTimeToStr(now) + 'Провал запроса: '+sql);
   ExceptionClose;
   result := -1;
 end;

end;


procedure TShowLastWesRec.Connect;
var  w:boolean;
begin

  if not rvgLogIn then Exit;

  if Connected then exit;

  w := true;



  WES.DatabaseName := url;

  WES.DBParams.Clear;

  WES.DBParams.Add('lc_ctype=WIN1251');
  WES.DBParams.Add('user_name=' + user);
  WES.DBParams.Add('password=' + pass);

  WES.SQLDialect := 3;


  WES.DefaultTransaction := Trans;
  qry.Database := WES;
  qry.ParamCheck := true;
  qry.Transaction := Trans;


  if NOT w then
    begin
      Connected := false;
      exit;
    end;


//    if WES.Connected then log ('TShowLastWesRec.Connect 5 было подключено!!!')
//                     else log ('TShowLastWesRec.Connect 5 было выключено');

    WES.Connected := true;
    if WES.Connected then
       begin
//        log ('TShowLastWesRec.Connect подключилось 6');
       end
    else
       begin
         w := false;
//         log ('TShowLastWesRec.Connect не подключилось 6!!!');
       end;
  try

  except
    WES.Connected := false;
    ShowMessage('Соединиться с весовой БД не удалось '+ url);
  end;

  Connected := w;
end;

procedure TShowLastWesRec.Disconnect;
begin
  Connected := false;
  if WES.Connected then
    begin
//      log ('TShowLastWesRec.Disconnect пытаемся');
      WES.Connected := false;
//      if WES.Connected then log ('TShowLastWesRec.Disconnect не получилось!!!')
//                       else log ('TShowLastWesRec.Disconnect получилось');

    end  else
    begin
//      log ('TShowLastWesRec.Disconnect нечего отключать');
    end;
end;


end.
