{
    Author: Hert van Zwietering
    Initial Date: 09 nov 2020

    Version history:
        1.0
            09 nov 2020;
            initial version
}

  function HandleImageItem(AImageItem: TImageItem): Integer;
  var
    AAreas: TCatalogAreas;
    AArea: TCatalogArea;
    i: Integer;
  begin
    result := 0;
    AAreas := TCatalogAreas.Create(TCatalogArea, '');
    try
      PublicCatalog.EnumAreasForImage(AImageItem, AAreas);
      for i := 0 to AAreas.Count - 1 do
      begin
        AArea := AAreas.Items[i];

        if AArea.PropGUID = '' then
        begin
          PublicCatalog.DeleteArea(AArea, False);
          result := result + 1;
        end;
      end;
    finally
      AAreas.Free;
    end;
  end;

var
  i, AHit: Integer;
  AProgress: TxomProgress;
begin
  if Selected.Count = 0 then
  begin
    Say ('No images selected');
    exit;
  end;

  if not Ask ('This script will delete all Areas that are not linked to a Catalog Label for the ' + IntToStr(Selected.Count) + ' selected thumbnails.' + CrLf2 + 'Are you sure you want to continue?') then
    exit;

  AProgress := TxomProgress.Create(nil);
  try
    AProgress.Caption := 'Delete all areas';
    AProgress.Cancel := False;
    AProgress.ProgressBar := True;
    AProgress.Max := Selected.Count;
    AProgress.Show;

    AHit := 0;
    for i := 0 to Selected.Count - 1 do
    begin
      AProgress.ProgressText := Selected.Items[i].FileName;
      AProgress.Pos := i + 1;
      if AProgress.Cancel then
        break;

      AHit := AHit + HandleImageItem(Selected.Items[i]);
    end;

    AProgress.Hide;
    if AProgress.Cancel then
      Say('Cancelled after already deleting ' + IntToStr(AHit) + ' unlinked areas')
    else
      Say2('Finished.', 'Deleted ' + IntToStr(AHit) + ' unlinked areas');
  finally
    AProgress.Free;
  end;
end;

