#!/usr/bin/perl
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

use Text::vCard::Addressbook;

  my $address_book = Text::vCard::Addressbook->new({
        'source_file' => 'cards/Alliance_Pharmacy.vcf',
  });

print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
print "<qof-qsf xmlns=\"http://qof.sourceforge.net/\">\n";
print "  <book count=\"1\">\n";
print "    <book-guid/>\n";
print "    <object type=\"pilot_address\" count=\"1\">\n";

  foreach my $vcard ($address_book->vcards()) {
 	my $names = $vcard->get({ 'node_type' => 'name' });
	foreach my $name (@{$names}){
		&wrap_in_qsf($name->family(), "entryLastname");
		&wrap_in_qsf($name->given(), "entryFirstname");
	}
	my $phones = $vcard->get('tel');
	my $i = 1;
	foreach my $phone (@{$phones}){
		$e = "entryPhone" . $i;
		&wrap_in_qsf($phone->value(), $e);
		$i++;
	}
	for($ii = $i; $ii < 5; $ii++)
	{
		$e = "entryPhone" . $ii;
		&wrap_in_qsf('', $e);
	}
	$email = $vcard->get('email');
	foreach my $e (@{$email}){ &wrap_in_qsf($e->value(), "entryPhone5"); }
 	$addresses = $vcard->get({ 'node_type' => 'addresses' });
	foreach my $address (@{$addresses}) {
	        &wrap_in_qsf($address->street(), "entryAddress");
	        &wrap_in_qsf($address->city(), "entryCity");
	        &wrap_in_qsf($address->region(), "entryState");
	        &wrap_in_qsf($address->post_code(), "entryZip");
	        &wrap_in_qsf($address->country(), "entryCountry");
	}
  }
print "    </object>\n";
print "  </book>\n";
print "</qof-qsf>\n\n";

sub wrap_in_qsf()
{
	if($_[0]) { print "      <string type=\"$_[1]\">$_[0]</string>\n"; }
	else { print "      <string type=\"$_[1]\"/>\n"; }
};
