unit uUploadPicture;

interface

uses
  Windows,SysUtils, Classes,Vcl.Graphics,System.IOUtils,Math,Dialogs,
  uniGUIBaseClasses, uniGUIClasses, uniFileUpload, IdBaseComponent,uniGUIForm, uniGUITypes,
   IdComponent, IdIPWatch, System.SyncObjs, IdTCPConnection, IdTCPClient, IdHTTP,
   uniImage,
   Vcl.ExtCtrls,JPeg,PNGImage // << for timage
   ;

  {
  Windows, Messages, SysUtils, Variants, Classes, Graphics,
  Controls, Forms, Dialogs, uniGUIForm, uniGUITypes, UniFileUpload, StdCtrls,
  UniLabel, Buttons, UniBitBtn, ExtCtrls, UniImage, UniPanel, uniGUIRegClasses,  uniguiclasses,
  UniButton, uniGUIBaseClasses;
  }

type
  TUploadPicture = class(TDataModule)
    UniFileUpload: TUniFileUpload;
    IdIPWatch: TIdIPWatch;
    IdHTTP: TIdHTTP;
    procedure UniFileUploadCompleted(Sender: TObject; AStream: TFileStream);
    procedure DataModuleCreate(Sender: TObject);

  private

    FUniImage:TUniImage;

    function CreateUniqueNameAddingGUID(FileName: string; MaxOriginNameLength: Integer): string;
    {<Creating New Unique Name with a rest of old name, using GUID}

    { Private declarations }
  public
    { Public declarations }

    property UniImage:TUniImage read FUniImage write FUniImage;


  end;



function UploadPicture: TUploadPicture;

implementation

{$R *.dfm}

uses
  UniGUIVars, uniGUIMainModule, MainModule,
  ServerModule,uDiminishPic,Main,uAddProductForm,
  uDataBaseUnit;

function UploadPicture: TUploadPicture;
begin
  Result := TUploadPicture(UniMainModule.GetModuleInstance(TUploadPicture));
end;

{ TUploadPicture }

procedure TUploadPicture.DataModuleCreate(Sender: TObject);
begin

  if not DirectoryExists(UniServerModule.StartPath+'UploadFolder\') then
    CreateDir(UniServerModule.StartPath+'UploadFolder\');

 if not DirectoryExists(UniServerModule.StartPath+'UploadFolder\Thumbnails') then
    CreateDir(UniServerModule.StartPath+'UploadFolder\Thumbnails');

end;




procedure TUploadPicture.UniFileUploadCompleted(Sender: TObject; AStream: TFileStream);
var
  DestName : string;
  DestFolder : string;
  FilePathOnServer: string;
  ServerResponse: string;
  ProtocolServerAndPort: string;
  FileExtension: string;
  ThumbnailFileName: string;
  bmp: TBitmap;

  var  NewFileName:string;
       Params:string;

       uniimageSource:TUniImage;
       uniimageDest:TUniImage;

  //     LDiminishPic:TDiminishPic;

begin


    DestFolder:=UniServerModule.StartPath+'UploadFolder\';

    NewFileName:=CreateUniqueNameAddingGUID(UniFileUpload.FileName, 15);

    DestName:=DestFolder+NewFileName;//ExtractFileName(UniFileUpload.FileName);


    //UniLabel4.Caption:='File Name: '+UniFileUpload.FileName;

    CopyFile(PChar(AStream.FileName), PChar(DestName), False);


    ForceDirectories(DestFolder+'thumbnails\');

{
    //CreateThumbnailOnServer
    ProtocolServerAndPort:='http://'+IdIPWatch.LocalIP+':'+UniServerModule.Port.ToString;

    Params:='?'+
    'PicPath='+DestName+'&'+
    'FileName='+NewFileName;

//    ServerResponse:=IdHTTP.Get(ProtocolServerAndPort+'/CreateThumbnailOnServer'+Params); //?login=admin&password=qwerty&someparam=someparamvalue');
//    if ServerResponse='wow' then
//     MainForm.UniSession.AddJS(' alert('''+ServerResponse+''');    ');
}

//       uniimageSource:=TUniImage.Create(UniMainModule.UniApplication);
//       uniimageDest:=TUniImage.Create(UniMainModule.UniApplication);


//   LDiminishPic:=TDiminishPic.Create(UniMainModule.UniApplication);

bmp:=TBitmap.Create;

   DiminishPic.ProportionalDiminishPicSize2(

   DestName,
   128,
   128,
   bmp

   );

  FileExtension:='.bmp'; //ExtractFileExt(NewFileName);
  ThumbnailFileName:=ChangeFileext( NewFileName, '_thumb'+FileExtension );

  bmp.SaveToFile(DestFolder+'thumbnails\'+ThumbnailFileName);
  fAddProductForm.UniImage.Picture.Bitmap.Assign(bmp);// .LoadFromFile(DestFolder+'thumbnails\'+ThumbnailFileName);

  //Updating image links in DB


with  DataBaseUnit.qUpdateImageLink do begin

      Params.ParamValues['ImageLink']:=DestName;
      Params.ParamValues['id']:=fAddProductForm.MaxInsertedID;
      ExecSQL;

end;

with  DataBaseUnit.qUpdateImageThumbnailLink do begin

      Params.ParamValues['ImageThumbnailLink']:=DestFolder+'thumbnails\'+ThumbnailFileName;
      Params.ParamValues['id']:=fAddProductForm.MaxInsertedID;
      ExecSQL;

end;


fAddProductForm.eImageLinkOnServer.Text:=DestName;


end;



function TUploadPicture.CreateUniqueNameAddingGUID(FileName: string; MaxOriginNameLength: Integer): string;

var
    Extension:string;
    SplittedString: TArray<String>;
    SomeStringToChange: string;
    newguid:tguid;
    i: Integer;

    FileNameTemp:string;

begin

//Checks
if FileName='' then Exit;
//if MaxOriginNameLength=0 then exit;  // if MaxOriginNameLength=0 will be only GUID as a result


//1--------- First of all we need to extract extension if it is
SplittedString:=FileName.Split(['.']);

    //we suppose that extensions are symbols after last '.', so...

    // if FileName has extension like 'SomeFileName.exe'

    if Length(SplittedString)>0 //1 and more, for example somename.ext [somename,ext]
    then

begin
    Extension:=SplittedString[ High(SplittedString)  ];


    //Lets join everything except extension
      for i := Low(SplittedString) to High(SplittedString)-1 do
         begin

         if i=0 then
         SomeStringToChange:=SomeStringToChange+SplittedString[i] else
         SomeStringToChange:=SomeStringToChange+'.'+SplittedString[i];
         end;

         //Cutting name up to the MaxOriginNameLength
      if Length( SomeStringToChange )> MaxOriginNameLength then
      SomeStringToChange:=SomeStringToChange.Substring(0,MaxOriginNameLength);

      //Adding GUID
      Createguid(newguid);
      SomeStringToChange:=SomeStringToChange+newguid.ToString;

      // Joining Extension
      SomeStringToChange:=SomeStringToChange+'.'+Extension;

      Result:=SomeStringToChange;
{
//ShowMessage(Extension);

//2----------Now lets change previous massive Element if it is

      SomeStringToChange:=SplittedString[ High(SplittedString)-1  ];

      //Cutting name up to the MaxOriginNameLength
      if Length( SomeStringToChange )> MaxOriginNameLength then
      SomeStringToChange:=SomeStringToChange.Substring(0,MaxOriginNameLength);

      //Adding GUID
      Createguid(newguid);
      SomeStringToChange:=SomeStringToChange+newguid.ToString;

      SplittedString[ High(SplittedString)-1  ]:=SomeStringToChange;

//3-------Now our name is Unique we can join it back


                for i := Low(SplittedString) to High(SplittedString)-1 do
                Result:=Result+SplittedString[i]+'.';

                //At last adding Extension
                Result:=Result+Extension;

}


end else

     // if FileName without Extension like 'SomeFileName'
     if Length(SplittedString)=0 then

     begin

     FileNameTemp:=FileName;


      //Cutting name up to the MaxOriginNameLength
      if Length( FileNameTemp )> MaxOriginNameLength then
      FileNameTemp:=FileNameTemp.Substring(0,MaxOriginNameLength);

      //Adding GUID
      Createguid(newguid);
      FileNameTemp:=FileNameTemp+newguid.ToString;


      Result:=FileNameTemp;
     end;

//ShowMessage(Result);
end;



initialization
  RegisterModuleClass(TUploadPicture);





end.
