unit uActualizarProveedoresUtils;

interface

uses
  Forms, Classes, Windows, SysUtils,
  uBizTiendaWeb, JSDialog, ExtCtrls;

function ActualizarProveedoresTienda(ATiendaWeb : IBizTiendaWeb): Boolean;

implementation

uses
  uProveedoresController, uOscManufacturersController,
  uBizOscManufacturers, uPasswordUtils, schTiendaWebClient_Intf, uDADataTable,
  uBizContactos, uBizDireccionesContacto, schContactosClient_Intf,
  JSDialogs, uDialogUtils, StrUtils, uIntegerListUtils;


function AnadirOSCManufacturer(AOSCManufacturers : IBizOscManufacturer; AProveedor : IBizProveedor): Boolean;
var
  AOSCManufacturerController : IOscManufacturersController;
  i : Integer;
  Resultado : Boolean;
begin
  Result := True;

  if not Assigned(AOSCManufacturers) then
    raise Exception.Create ('OSCManufacturers no asignado (AnadirOSCManufacturer)');

  if not Assigned(AProveedor) then
    raise Exception.Create ('Proveedor no asignado (AnadirOSCManufacturer)');

  AProveedor.DataTable.Active := True;

  AOSCManufacturerController := TOscManufacturersController.Create;
  AOSCManufacturers.DataTable.Active := True;

  try
    AOSCManufacturerController.Anadir(AOSCManufacturers);
    with AOSCManufacturers do
    begin
      manufacturers_name := AProveedor.NOMBRE;
      date_added := Now;
      rdx_manufacturers_id_local := AProveedor.ID;
      Post;
    end;
    AOSCManufacturerController.Guardar(AOSCManufacturers);
    
  finally
    AOSCManufacturerController := NIL;
  end;
end;


function ActualizarOSCManufacturer(AOSCManufacturers : IBizOscManufacturer; AProveedor : IBizProveedor) : Boolean;
var
  AOSCManufacturerController : IOscManufacturersController;
  i : Integer;
  Resultado : Boolean;  
begin
  Result := True;

  if not Assigned(AOSCManufacturers) then
    raise Exception.Create ('OSCManufacturers no asignado (ActualizarOSCManufacturer)');

  if not Assigned(AProveedor) then
    raise Exception.Create ('Proveedor no asignado (ActualizarOSCManufacturer)');

  AProveedor.DataTable.Active := True;

  AOSCManufacturerController := TOscManufacturersController.Create;

  AOSCManufacturers.DataTable.Active := True;
  try
    if not AOSCManufacturerController.Localizar(AOSCManufacturers, AProveedor.ID) then
      raise Exception.CreateFmt('No se ha localizado el manufacturer con ID = %d', [AProveedor.ID]);

    with AOSCManufacturers do
    begin
      Edit;
      manufacturers_name := AProveedor.NOMBRE;
      last_modified := Now;
      Post;
    end;
    AOSCManufacturerController.Guardar(AOSCManufacturers);
    
  finally
    AOSCManufacturerController := NIL;
  end;
end;

function HayCambiosPendientes(AProveedor : IBizProveedor; const UltimaSincro : TDateTime): Boolean;
begin
  if not Assigned(AProveedor) then
    raise Exception.Create ('Proveedor no asignado (HayCambiosPendientes)');

  AProveedor.DataTable.Active := True;

  Result := (AProveedor.FECHA_MODIFICACION > UltimaSincro);
end;

function ActualizarProveedoresTienda(ATiendaWeb : IBizTiendaWeb): Boolean;
var
  AProveedoresController : IProveedoresController;
  AProveedores : IBizProveedor;

  AOSCManufacturerController : IOscManufacturersController;
  AOSCManufacturers : IBizOscManufacturer;

  i : Integer;

  //ADlg : TJSDialog;
  Resultado : Boolean;
  s : String;

  AManufacturerList : TIntegerList;
  AIndex : Integer;
begin
  Result := False;
  if not Assigned(ATiendaWeb) then
    raise Exception.Create ('TiendaWeb no asignada');

  AProveedoresController := TProveedoresController.Create;
  AOSCManufacturerController := TOscManufacturersController.Create;

  AManufacturerList := TIntegerList.Create;
  //ADlg := TJSDialog.Create(nil);
  try
    {with ADlg do
    begin
      Title := 'Actualización de proveedores';
      DialogOptions := [doProgressBarMarquee, doTopMost];
      ButtonBar.Buttons := [];
      Instruction.Text := 'Actualizando proveedores...';
      Content.Text := Format('Progreso: %d%%', [0]);
      Expando.Visible := True;
      Expando.MoreHeight := 200;
      Expando.ShowInFooter := True;
      Expando.ShowText := 'Ver más detalles...';
      Expando.HideText := 'Ocultar detalles...';
      Progress.Max := 100;
    end;}

    AProveedores := (AProveedoresController.BuscarTodosTiendaWeb as IBizProveedor);
    AProveedores.DataTable.Active := True;
    AProveedores.DataTable.First;

    AOSCManufacturers := AOSCManufacturerController.BuscarTodos;
    AOSCManufacturers.DataTable.Active := True;
    AOSCManufacturers.DataTable.First;

    {if AProveedores.DataTable.RecordCount > 0 then
      ADlg.Progress.Max := AProveedores.DataTable.RecordCount;

    ADlg.Execute;
    Application.ProcessMessages;}
    
    for I := 0 to AProveedores.DataTable.RecordCount - 1 do
    begin
      Application.ProcessMessages;
      {with ADlg do
      begin
          Content.Text := Format('Progreso: %d%%', [Progress.Position*100 div ADlg.Progress.Max]);
          //UpdateProgress;
          Application.ProcessMessages;
      end;}

      if not AOSCManufacturerController.Localizar(AOSCManufacturers, AProveedores.ID) then
      begin
        s := Format('Añadiendo %s... ', [AProveedores.NOMBRE]);
        Resultado := AnadirOSCManufacturer(AOSCManufacturers, AProveedores);
        if Resultado then
          s := s + 'OK'
        else
          s := s + 'Fallo';
      end
      else begin
        if HayCambiosPendientes(AProveedores, ATiendaWeb.ULTIMA_ACTUALIZACION) then
        begin
          s := Format('Actualizando %s... ', [AProveedores.NOMBRE]);
          Resultado := ActualizarOSCManufacturer(AOSCManufacturers, AProveedores);
          if Resultado then
            s := s + 'OK'
          else
            s := s + 'Fallo';
        end
        else
          s := Format('%s sin cambios', [AProveedores.NOMBRE]);
      end;

      //ADlg.Expando.Lines.Add(s);

      AManufacturerList.Add(AProveedores.ID);
      AProveedores.DataTable.Next;

      {with ADlg do
      begin
        Content.Text := Format('Progreso: %d%%', [Progress.Position*100 div ADlg.Progress.Max]);
        //UpdateProgress;
        Application.ProcessMessages;
      end;}
    end;

    // Ahora hay que eliminar de OSC los proveedores que sobran
    AOSCManufacturers.Last;
    for I := (AOSCManufacturers.DataTable.RecordCount - 1) downto 0 do
    begin
      Application.ProcessMessages;    
      if not AManufacturerList.Find(AOSCManufacturers.rdx_manufacturers_id_local, AIndex) then
      begin
        s := Format('Eliminado %s... ', [AOSCManufacturers.manufacturers_name]);
        //ADlg.Expando.Lines.Add(s);
        AOSCManufacturers.Delete;
      end;
      AOSCManufacturers.Prior;
    end;

    AOSCManufacturerController.Guardar(AOSCManufacturers);
    Application.ProcessMessages;
    Result := True;
  finally
    {ADlg.Close;
    FreeAndNIL(ADlg);
    Application.ProcessMessages;}
    

    FreeAndNIL(AManufacturerList);

    AProveedores.DataTable.Active := False;
    AProveedores := NIL;

    AOSCManufacturers.DataTable.Active := False;
    AOSCManufacturers := NIL;

    AProveedoresController := NIL;
    AOSCManufacturerController := NIL;
  end;
end;


end.
