unit VCardProcessor;

interface

uses
  Classes, SysUtils, VCard;

type

  { TVCardProcessor }

  TVCardProcessor = class(TComponent)
  public
    RemovePhoneSpaces: Boolean;
    RemovePhotos: Boolean;
    AddDefaultPhoneCountryPrefix: Boolean;
    DefaultPhoneCountryCode: string;
    ConvertInternationalCallPrefixToCountryCode: Boolean;
    DefaultInternationalCallPrefix: string;
    NonPrefixedPhoneLength: Integer;
    RemoveExactDuplicates: Boolean;
    Order: Boolean;
    procedure Process(VCard: TVCard);
    constructor Create(AOwner: TComponent); override;
  end;


implementation

function RemoveSpaces(Text: string): string;
begin
  Result := StringReplace(Text, ' ', '', [rfReplaceAll]);
end;

{ TVCardProcessor }

procedure TVCardProcessor.Process(VCard: TVCard);
var
  I: Integer;
  J: Integer;
  ContactProperties: TContactProperties;
  Value: string;
begin
  for I := 0 to VCard.Contacts.Count - 1 do
  with TContact(VCard.Contacts[I]) do begin
    if RemovePhoneSpaces or AddDefaultPhoneCountryPrefix or
      ConvertInternationalCallPrefixToCountryCode then begin
      ContactProperties := Properties.GetMultipleByName('TEL');
      try
        for J := 0 to ContactProperties.Count - 1 do begin
          if RemovePhoneSpaces then
            ContactProperties[J].Value := RemoveSpaces(ContactProperties[J].Value);
          if AddDefaultPhoneCountryPrefix and (NonPrefixedPhoneLength > 0) then begin
            Value := ContactProperties[J].Value;
            if (Length(Trim(Value)) > 0) and (Trim(Value)[1] in ['0'..'9']) and
              (Length(RemoveSpaces(Value)) = NonPrefixedPhoneLength) then
            ContactProperties[J].Value := DefaultPhoneCountryCode + Value;
          end;
          if ConvertInternationalCallPrefixToCountryCode then begin
            if ContactProperties[J].Value.StartsWith(DefaultInternationalCallPrefix) then
              ContactProperties[J].Value := DefaultPhoneCountryCode + Copy(ContactProperties[J].Value, Length(DefaultInternationalCallPrefix) + 1, MaxInt);
          end;
        end;
      finally
        ContactProperties.Free;
      end;
    end;

    if RemovePhotos then begin
      ContactProperties := Properties.GetMultipleByName('PHOTO');
      try
        for J := ContactProperties.Count - 1 downto 0 do
          Properties.Remove(ContactProperties[J]);
      finally
        ContactProperties.Free;
      end;
    end;
  end;

  if RemoveExactDuplicates then begin
    VCard.Contacts.RemoveExactDuplicates;
    for I := 0 to VCard.Contacts.Count - 1 do
      VCard.Contacts[I].Properties.RemoveExactDuplicates;
  end;

  if Order then begin
    VCard.Contacts.Sort;
  end;

  VCard.Modified := True;
end;

constructor TVCardProcessor.Create(AOwner: TComponent);
begin
  inherited;
  NonPrefixedPhoneLength := 9;
end;

end.

