unit uGenerateUniqueCode;

interface

uses
  SysUtils, Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
  FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
  FireDAC.Comp.Client;

type
  TGenerateUniqueCode = class(TDataModule)
    qSelectAllCodes: TFDQuery;
    qInsertNewCode: TFDQuery;
    procedure DataModuleCreate(Sender: TObject);
  private
    { Private declarations }

    FSessionID:integer;

    FMainForm:TObject;

    function IsSuchCodeInDB(code:integer):Boolean;
    function IfZero(x: integer): string;



  public
    { Public declarations }

    function GenerateUniqueCode:integer;

    property SessionID:integer read FSessionID write FSessionID;
    property MainForm:TObject read FMainForm write FMainForm;

  end;

function GenerateUniqueCode: TGenerateUniqueCode;

implementation

{$R *.dfm}

uses
  UniGUIVars, uniGUIMainModule, MainModule,Main, uDBConnection;

var MainForm_UnitVar:TMainForm;


function GenerateUniqueCode: TGenerateUniqueCode;
begin
  Result := TGenerateUniqueCode(UniMainModule.GetModuleInstance(TGenerateUniqueCode));
end;


procedure TGenerateUniqueCode.DataModuleCreate(Sender: TObject);
begin
//
 if (Sender is TMainForm) then

 begin

 MainForm_UnitVar:=(Sender as TMainForm);
 qSelectAllCodes.Connection:=UniMainModule.DBConnection.FDConnection;
 qInsertNewCode.Connection:=UniMainModule.DBConnection.FDConnection;

 end;




end;


function TGenerateUniqueCode.IfZero(x:integer): string;
begin


   if x=0 then Result:='0' else Result:=x.ToString;


end;

function TGenerateUniqueCode.GenerateUniqueCode: integer;

var code:integer;
    codestring:string;

    c1,c2,c3,c4:integer;

begin

 Randomize;

 repeat

   c1:=Random(9);
   c2:=Random(9);
   c3:=Random(9);
   c4:=Random(9);



   codestring:=    // << must be 4 digits here, //Random(9999) gives any number of digits
    IfZero(c1) +
     IfZero(c2)+
      IfZero(c3)+
       IfZero(c4);

   code:=codestring.tointeger;

 until not IsSuchCodeInDB(code);


 with  qInsertNewCode do begin

 Connection:=UniMainModule.DBConnection.FDConnection;
 Params.ParamValues['CODE']:=code.ToString;
 Params.ParamValues['Sessions_id']:=FSessionID;
 ExecSQL;

 end;

 Result:=code;

end;

function TGenerateUniqueCode.IsSuchCodeInDB(code: integer):Boolean;
begin

Result:=false;

qSelectAllCodes.Connection:=UniMainModule.DBConnection.FDConnection;

with qSelectAllCodes do begin
Open;

 while not Eof  do begin

 if FieldByName('Code').AsInteger=code then Result:=True;
 Break;

 Next;
 end;

Close;
end;



end;

initialization
  RegisterModuleClass(TGenerateUniqueCode);

end.
