unit uSvcCustom;

interface
{$I 'GlobalDefs.inc'}

uses
  System.Classes,
  System.JSON,
  System.Generics.Collections,
  Winapi.ActiveX,
  System.DateUtils,
  System.SysUtils,
  JsonDataObjects,
  uSvc_Base,
  uCommons, // kvuli EServiceException
  helTabsBIDs,
  uHeoObj_Base,
  uHeOObj_Custom,
  uHeoObj_Vyroba,
  uSvc_Obecne,
  uSvc_ObehZbozi,
  uSvc_Vyroba;


const
//{$I C:\_zakaznici\pluginy_obecne\HDCApi2\globalConsts.inc}
{$I .\..\..\globalConsts.inc}

 selSloupce = 'SELECT TypZakazky, CisloZakazky, NazevOrg, CisloOrg, VyrobniCislo, NazevPol, idPolozkaObj, PotvrzenyTerminDod, NadrazeneCisloZakazky, Vykres, Stav'
            + ', ID AS IDZakazky, Nazev, DruhyNazev, DatPorizeni_Y FROM dbo.hvw_ADE_VIEW_ZAKAZKA ORDER BY CisloZakazky';

 selEMPAtestDok = 'SELECT d.ID, d.Popis, d.JmenoACesta, ISNULL(de_CisloAtestu, N'''') AS CisloAtestu, ISNULL(de._AtestyPoznamka, N'''') AS AtestPoznamka'
                  + ', d.DatPorizeni FROM ' + tblDokum + ' d LEFT JOIN ' + tblDokumE + ' de ON (de.ID=d.ID)';

type
  TEMPNadobaService = class(TServiceBase)
   public
    function GetAll: TObjectList<TEMPNadoba>;
    function GetByID (const AID: integer): TEMPNadoba;
    function GetByCislo (const ACislo: string): TEMPNadoba;
    function GetMeta: TJSONObject;
    function GetByParams (params: TDictionary<string, string>): TObjectList<TEMPNadoba>;
  end;

  TEMPVytezeniDoklService = class(TServiceBase)
   public
    function FPrij_PostByID (const AID: integer): TJSONObject; // vrati se identifikace od providera
  end;



implementation
uses
  System.StrUtils,
  FireDAC.Stan.Option,
  FireDAC.Comp.Client,
  FireDAC.Stan.Param,
  System.JSON.Builders,
  System.JSON.Writers,
  System.JSON.Types,
  MVCFramework.FireDAC.Utils,
  MVCFramework.DataSet.Utils,
  MVCFramework.Serializer.Commons,
  uCtrlBase
  ;




{ TEMPNadobaService }

 function TEMPNadobaService.GetByParams (params: TDictionary<string, string>): TObjectList<TEMPNadoba>;
  var lSQL, where, ordBy: string;
      AID, cnt, rNo: integer;
      retObj: TEMPNadoba;
      lsRetObj: TObjectList<TEMPNadoba>;
      lQry: TFDQuery;
      sqlConnX: TFDConnection;
  begin
   result:= nil;

   ordBy:= 'VyrobniCislo';

   if (params<>nil) then
    begin
     if (params.ContainsKey('ordBy')) then
      if (params.Items['ordBy']<>'') then
       ordBy:= params.Items['ordBy'];
    end;

   lSQL:= 'SELECT ' + selSloupce;
   lSQL:= lSQL + ' ORDER BY ' + ordBy;


   sqlConnX:= TFDConnection.Create(nil);
   sqlConnX.ConnectionDefName:= sqlPoolName;

   lQry:= TFDQuery.Create(nil);
   try
     lQry.FetchOptions.Mode:= fmAll;
     lQry.Connection:= sqlConnX;
     lQry.Open(lSQL);
     cnt:= lQry.RecordCount;
     if (cnt>0) then
      begin
       lsRetObj:= TObjectList<TEMPNadoba>.Create;
       try
         lQry.First;
         rNo:= 1;
         while (rNo<=cnt) do
          begin
           lQry.RecNo:= rNo;
           AID:= lQry.FieldByName('ID').AsInteger;
           retObj:= self.GetByID (AID);
           lsRetObj.Add(retObj);
           if not(lQry.Active) then
            lQry.Open;
           Inc (rNo);
          end;
         Result:= lsRetObj;
        except on E:Exception do
         raise EServiceException.Create('Chyba nacitani nadob: ' + E.Message);
       end;
      end;
    except on E:Exception do
     raise EServiceException.Create(errMaterialy + E.Message);
   end;

   lQry.Free;
   sqlConnX.Close;
   sqlConnX.Free;

  end;




 function TEMPNadobaService.GetAll:TObjectList<TEMPNadoba>;
  var lSQL: string;
  begin
   lSQL:= selSloupce + ' ORDER BY VyrobniCislo';
   FDM.sqlQry1.Open(lSQL, []);
   result:= FDM.sqlQry1.AsObjectList<TEMPNadoba>;
   FDM.sqlQry1.Close;
  end;




 function TEMPNadobaService.GetByID (const AID: Integer): TEMPNadoba;
  var lSQL: string;
      lQry: TFDQuery;
      sqlConnX: TFDConnection;
  begin
   lSQL:= selSloupce + ' WHERE ID=:ID';

   sqlConnX:= TFDConnection.Create(nil);
   sqlConnX.ConnectionDefName:= sqlPoolName;

   lQry:= TFDQuery.Create(nil);
   try
     lQry.FetchOptions.Mode:= fmAll;
     lQry.Connection:= sqlConnX;
     lQry.Open(lSQL, [AID]);
     lQry.First;
     try
       if not(lQry.EOF) then
         begin
       result:= FDM.sqlQry1.AsObject<TEMPNadoba>
         end
       else
         raise EServiceException.Create('Nádoba s ID ' + AID.ToString + ' nebyla nalezena.');
      except on E:Exception do
       raise EServiceException.Create('Nádoba s ID ' + AID.ToString + ' nebyla nalezena - ' + E.Message);
     end;
    finally
     lQry.Free;
   end;

   sqlConnX.Close;
   sqlConnX.Free;
  end;




 function TEMPNadobaService.GetByCislo (const ACislo: string): TEMPNadoba;
  var lSQL: string;
      lQry: TFDQuery;
      sqlConnX: TFDConnection;
  begin
   lSQL:= selSloupce + ' WHERE VyrobniCislo=:ACislo';

   sqlConnX:= TFDConnection.Create(nil);
   sqlConnX.ConnectionDefName:= sqlPoolName;

   lQry:= TFDQuery.Create(nil);
   try
     lQry.FetchOptions.Mode:= fmAll;
     lQry.Connection:= sqlConnX;
     lQry.Open(lSQL, [ACislo]);
     lQry.First;
     try
       if not(lQry.EOF) then
         begin
          result:= FDM.sqlQry1.AsObject<TEMPNadoba>;
         end
       else
         raise EServiceException.Create('Nádoba s číslem ' + ACislo + ' nebyla nalezena.');
      except on E:Exception do
       raise EServiceException.Create('Nádoba s číslem ' + ACislo + ' nebyla nalezena - ' + E.Message);
     end;
    finally
     lQry.Free;
   end;

   sqlConnX.Close;
   sqlConnX.Free;
  end;




 function TEMPNadobaService.GetMeta: TJSONObject;
  var lSQL: string;
      lQry: TFDQuery;
      sqlConnX: TFDConnection;
  begin
   lSQL:= selSloupce + ' WHERE 1=0';

   sqlConnX:= TFDConnection.Create(nil);
   sqlConnX.ConnectionDefName:= sqlPoolName;

   lQry:= TFDQuery.Create(nil);
   try
     lQry.FetchOptions.Mode:= fmAll;
     lQry.Connection:= sqlConnX;
     lQry.Open(lSQL);
     result:= lQry.MetadataAsJSONObject();
    finally
     lQry.Free;
   end;

   sqlConnX.Close;
   sqlConnX.Free;

  end;




{ TEMPVytezeniDoklService }

 function TEMPVytezeniDoklService.FPrij_PostByID (const AID: integer): TJSONObject; // vrati se identifikace od providera
  var lSQL, statusOut: string;
      resVal: TJSONObject;
      sB: TStringBuilder;
      sW: TStringWriter;
      w: TJsonTextWriter;
      b: TJSONObjectBuilder;
      p: TJSONCollectionBuilder.TPairs;
  begin
   result:= TJSONObject.Create;
   statusOut:= 'Not OK';

   sB:= TStringBuilder.Create;
   sW:= TStringWriter.Create (sB);
   w:= TJsonTextWriter (sW);
   w.Formatting:= TJsonFormatting.Indented;
   b:= TJsonObjectBuilder.Create (w);
   p:= b.BeginObject.Add('status', statusOut);
   p.EndObject;
   result.FromJSON (sB.ToString);
  end;


end.
