# -*- coding: utf-8 -*-
from AddressBook import *
import pprint

def addressBookToList():
        ab = ABAddressBook.sharedAddressBook()
        people = ab.people()

        peopleList = []

        for person in people:
                thisPerson = {}

		first  = person.valueForProperty_(kABFirstNameProperty);
		if type(first) == objc.pyobjc_unicode:
                	thisPerson['first'] = first
		last = person.valueForProperty_(kABLastNameProperty);
		if type(last) == objc.pyobjc_unicode:
                	thisPerson['last'] = last
		
		phones = person.valueForProperty_(kABPhoneProperty);
		if not type(phones) == ABMultiValueCoreDataWrapper:
			continue;

		for val in range(0,phones.count()):
			if phones.labelAtIndex_(val) == kABPhoneMobileLabel:
				thisPerson['mobile'] = telnormalize(phones.valueAtIndex_(val))
			if phones.labelAtIndex_(val) == kABPhoneHomeLabel:
				thisPerson['private'] = telnormalize(phones.valueAtIndex_(val))
			if phones.labelAtIndex_(val) == kABPhoneWorkLabel:
				thisPerson['work'] = telnormalize(phones.valueAtIndex_(val))
                peopleList.append(thisPerson)
        return peopleList

def telnormalize(tel):
	for c in ('-', ' ', '\t'):
		tel = tel.replace(c, '')

	# replace with your country code
	if tel.startswith('+49'):
		tel = tel.replace('+49','0')

	# replace with your international prefix
	if tel[0] == '+':
		return '00' + tel[1:]

	return tel

def asciify(string):
	string = string.replace(u'ö','oe')
	string = string.replace(u'ä','ae')
	string = string.replace(u'ü','ue')
	string = string.replace(u'Ö','Oe')
	string = string.replace(u'Ä','Ae')
	string = string.replace(u'Ü','Ue')
	string = string.replace(u'ß','ss')
	string = string.replace(u'&','und')
	string = string.replace(u'\'','')
	string = string.replace(u';','')
	return string

file = 'Vorname;Nachname;Telefonnummer;Telefonnummertyp;Kurzwahl;Kommentar;Vanity\n'

list = addressBookToList()
for person in list:
	if not person.has_key('private') and not person.has_key('mobile') and not person.has_key('work'):
		continue;
	if not person.has_key('first') and not person.has_key('last'):
		continue;

	name = "";
	if person.has_key('first'):
		name = asciify(person['first']);
	name += ";"
	if person.has_key('last'):
		name += asciify(person['last']);
	name += ";"

	if person.has_key('private'):
		file += name;
		file += person['private']
		file += ';p;;imported;\n'
	if person.has_key('mobile'):
		file += name;
		file += person['mobile']
		file += ';m;;imported;\n'
	if person.has_key('work'):
		file += name;
		file += person['work']
		file += ';g;;imported;\n'

print file,


