# -*- 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 this with your country code
	if tel.startswith('+49'):
		tel = tel.replace('+49','0')

	# replace this 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 privat;Telefonnummer mobil;Telefonnummer arbeit\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;

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

	if name == ";;":
		continue;

	file += name;
	if person.has_key('private'):
		file += person['private']
		file += ';'
	if person.has_key('mobile'):
		file += person['mobile']
		file += ';'
	if person.has_key('work'):
		file += person['work']
		file += ';'

	file += '\n';

print file,

