//
//  ABPerson.m
//  mySTEP
//
//  Created by Dr. H. Nikolaus Schaller on Mon Aug 18 2003.
//  Copyright (c) 2003 DSITRI. All rights reserved.
//

#import <AddressBook/AddressBook.h>
#import "Private.h"

@implementation ABPerson

+ (void) cancelLoadingImageDataForTag:(int) tag;
{
}

- (id) initWithUniqueId:(id) uid;
{
	self=[super initWithUniqueId:uid];
	if(self)
		{
		parentgroups=[[NSMutableArray array] retain];
		}
	return self;
}

- (id) init;
{
	self=[super init];
	if(self)
		{
		parentgroups=[[NSMutableArray array] retain];
		}
	return self;
}

- (id) initWithVCardRepresentation:(NSData *) vCardData;
{
	self=[super init];
	if(self)
		{
		NSString *str=[[[NSString alloc] initWithData:vCardData encoding:NSUTF8StringEncoding] autorelease];
		if(![self _decodeWithVCardScanner:[NSScanner scannerWithString:str] firstLine:nil])
			{
			[self release];
			return nil;
			}
		}
	return self;
}

- (void) dealloc;
{
	[parentgroups release];
	[super dealloc];
}

- (void) _addToParentGroup:(ABGroup *) grp; { [parentgroups addObject:grp]; [self _touch]; }

- (void) _removeFromParentGroup:(ABGroup *) grp; { [parentgroups removeObject:grp]; [self _touch]; }

- (NSArray *) parentGroups; { return parentgroups; }

- (NSString *) _imageFileName; { return [AB_IMAGES stringByAppendingPathComponent:[self uniqueId]]; }

- (int) beginLoadingImageDataForClient:(id<ABImageClient>) client;
{
	return 0;
}

- (BOOL) setImageData:(NSData *) d;
{
	if(d)
		return [d writeToFile:[self _imageFileName] atomically:YES];
	// remove file if existing
	return YES;
}

- (NSData*) imageData; { return [NSData dataWithContentsOfFile:[self _imageFileName]]; }

// from ABImageClient protocol

- (void) consumeImageData:(NSData*) data forTag:(int) tag;
{
}

#if OLD
- (NSString *) _stringForProperty:(NSString *) prop;
{ // get as printable string
	id val=[self valueForProperty:prop];
	if(!val)
		return @"";
	return [val description];
}
#endif

- (NSString *) _vCardTag; { return @"VCARD"; }

- (NSDictionary *) _propertiesToEncode;
{ // default properties and attributes
	return [NSDictionary dictionaryWithObjectsAndKeys:
		kABUIDProperty,
		@"UID",
//		@"CREATED", kCALCreatedProperty,
//		@"LASTMODIFIED", kCALModifiedProperty,
//		@"X-CALNAME", kCALCalendarNameProperty,
		
		kABPhoneProperty,
		@"TEL",
		kABEmailProperty,
		@"EMAIL",
		kABBirthdayProperty,
		@"BDAY",
		kABNoteProperty, 
		@"NOTE",
		kABHomePageProperty,
		@"URL",
		kABTitleProperty,
		@"TITLE",
		kABJobTitleProperty, 
		@"ROLE",
		kABOrganizationProperty, 
		@"ORG",
		kABNicknameProperty,
		@"X-NICKNAME",
		kABMaidenNameProperty, 
		@"X-MAIDENNAME",
		kABDepartmentProperty,
		@"X-DEPARTMENT",
		nil];
}

- (void) _encodeVCard:(NSMutableString *) s;
{
	NSEnumerator *e;
	ABGroup *g;
	[self _encodeTag:@"VERSION" attributes:nil value:@"3.0" to:s];
	[self _encodeTag:@"PRODID" attributes:nil value:@"-//DSITRI, Germany//mySTEP 1.10//EN" to:s];	// hard coded
	[super _encodeVCard:s];
// FN, N
	// [self _appendLine:[self _formatTag:vCalProperty attributes:nil value:val] to:dest];
	// ADR
	if([self imageData])
		{ // encode PHOTO as base64 data
		}
	e=[[self parentGroups] objectEnumerator];
	while((g=[e nextObject]))
		[self _encodeTag:@"CATEGORIES" attributes:nil value:[g valueForProperty:kABGroupNameProperty] to:s];
}

- (NSData *) vCardRepresentation;
{
	NSMutableString *vc=[NSMutableString string];
	[self _encodeTag:@"BEGIN" attributes:nil value:[self _vCardTag] to:vc];
	[self _encodeVCard:vc];
	[self _encodeTag:@"END" attributes:nil value:[self _vCardTag] to:vc];
	return [vc dataUsingEncoding:NSUTF8StringEncoding];
}

/* example of a vCard generated by MacOS X:
BEGIN:VCARD
VERSION:3.0
N:last;first;;;
FN:first last
EMAIL;type=INTERNET;type=HOME;type=pref:user@host.org
TEL;type=CELL:+49123456789
TEL;type=HOME;type=pref:+49987654321
item1.ADR;type=HOME;type=pref:;;street number;city;;ZIP;country
item1.X-ABADR:de
item2.ADR;type=WORK:;;street number;city;;ZIP;
item2.X-ABADR:de
URL:www.dsitri.de
BDAY;value=date:YYYY-MM-DD
PHOTO;BASE64:
TU0AKgAAAAgAFAD+AAQAAAABAAAAAAEAAAMAAAABADAAAAEBAAMAAAABADAAAAECAAMAAAADAAAA
/gEDAAMAAAABAAEAAAEGAAMAAAABAAIAAAERAAQAAAABAAA9oAEVAAMAAAABAAMAAAEWAAMAAAAB
....
//8AA6ABAAMAAAAB//8AAKACAAQAAAABAAAAMKADAAQAAAABAAAAMAAAAAAAAA==
CATEGORY:group1,group2
END:VCARD
*/

#if OLD

- (NSString *) _vCardEscape:(NSString *) str;
{
	// escape '\n', ',', ';', '\' properly
	return str;
}

- (void) _appendTag:(NSString *) tag withProperty:(NSString *) prop toMutableString:(NSMutableString *) vc;
{
	id val=[self valueForProperty:prop];
	if(!val)
		return;	// ignore
	if([val isKindOfClass:[ABMultiValue class]])
		{
		int i, count=[val count];
		for(i=0; i<count; i++)
			{ // loop through all elements
			NSString *primary=[val primaryIdentifier];
			[vc appendFormat:@"%@;TYPE=%@%@:%@\r\n", tag,
				[val labelAtIndex:i], 
				[[val identifierAtIndex:i] isEqualToString:primary]?@",pref":@"",	// preferred or not
				// might need to convert dependent on [val propertyType]
				[self _vCardEscape:[val valueAtIndex:i]]];
			}
		return;
		}
	[vc appendFormat:@"%@:%@\r\n", tag, [self _vCardEscape:val]];
}

- (NSData *) vCardRepresentation;
{
	NSMutableString *vc=[NSMutableString string];
	NSEnumerator *e;
	ABGroup *g;
#if OLD
	[vc appendString:@"BEGIN:VCARD\r\n"];
	[vc appendString:@"VERSION:3.0\r\n"];
	[vc appendFormat:@"FN:%@ %@\r\n", [self _stringForProperty:kABFirstNameProperty], [self _stringForProperty:kABLastNameProperty]];
	[vc appendFormat:@"N:%@;%@;;;\r\n", [self _stringForProperty:kABLastNameProperty], [self _stringForProperty:kABFirstNameProperty]];
	[self _appendTag:@"TEL" withProperty:kABPhoneProperty toMutableString:vc];
	[self _appendTag:@"EMAIL" withProperty:kABEmailProperty toMutableString:vc];
	// create ADR;type=home:; ; city;address;zip;country
	//	[vc appendFormat:@"ADR;TYPE=home:%@;%@;;;\r\n", [self _stringForProperty:kABLastNameProperty], [self _stringForProperty:kABFirstNameProperty]];
	// beware of multiple entries i.e. ABMultiValue containing NSDictionaries
	[self _appendTag:@"BDAY;value=date" withProperty:kABBirthdayProperty toMutableString:vc];
	[self _appendTag:@"NOTE" withProperty:kABNoteProperty toMutableString:vc];
	[self _appendTag:@"URL" withProperty:kABHomePageProperty toMutableString:vc];
	[self _appendTag:@"TITLE" withProperty:kABTitleProperty toMutableString:vc];
	[self _appendTag:@"X-NICKNAME" withProperty:kABNicknameProperty toMutableString:vc];
	[self _appendTag:@"X-MAIDENNAME" withProperty:kABMaidenNameProperty toMutableString:vc];
	[self _appendTag:@"ROLE" withProperty:kABJobTitleProperty toMutableString:vc];
	[self _appendTag:@"ORG" withProperty:kABOrganizationProperty toMutableString:vc];
	[self _appendTag:@"X-DEPARTMENT" withProperty:kABDepartmentProperty toMutableString:vc];
//	[self _appendTag:@"GEO", withProperty:kABRoleProperty toMutableString:vc];
	[self _appendTag:@"UID" withProperty:kABUIDProperty toMutableString:vc];
	if([self imageData])
		{ // encode PHOTO
		}
	e=[[self parentGroups] objectEnumerator];
	while((g=[e nextObject]))
		[vc appendFormat:@"CATEGORIES:%@\r\n", [self _vCardEscape:[g valueForProperty:kABGroupNameProperty]]];
	[vc appendString:@"END:VCARD\r\n"];
	// process overlong lines - insert @"\r\n  " after every 80 (look into standard!) characters
	return [vc dataUsingEncoding:NSUTF8StringEncoding];
#else
	[self _appendLine:@"BEGIN:VCARD" to:vc];
	[self _appendLine:@"VERSION:3.0" to:vc];
	// FN, N
	// [self _appendLine:[self _formatTag:vCalProperty attributes:nil value:val] to:dest];
	[self _appendProperty:kABPhoneProperty as:@"TEL" to:vc];
	[self _appendProperty:kABEmailProperty as:@"EMAIL" to:vc];
	// ADR
	[self _appendProperty:kABBirthdayProperty as:@"BDAY" to:vc];	// should set ;VALUE=DATE
	[self _appendProperty:kABNoteProperty as:@"NOTE" to:vc];
	[self _appendProperty:kABHomePageProperty as:@"URL" to:vc];
	[self _appendProperty:kABTitleProperty as:@"TITLE" to:vc];
	[self _appendProperty:kABNicknameProperty as:@"X-NICKNAME" to:vc];
	[self _appendProperty:kABMaidenNameProperty as:@"X-MAIDENNAME" to:vc];
	[self _appendProperty:kABJobTitleProperty as:@"ROLE" to:vc];
	[self _appendProperty:kABOrganizationProperty as:@"ORG" to:vc];
	[self _appendProperty:kABDepartmentProperty as:@"X-DEPARTMENT" to:vc];
	[self _appendProperty:kABUIDProperty as:@"UID" to:vc];
	if([self imageData])
		{ // encode PHOTO as base64 data
		}
	e=[[self parentGroups] objectEnumerator];
	while((g=[e nextObject]))
		[self _appendLine:[self _formatTag:@"CATEGORIES" attributes:nil value:[g valueForProperty:kABGroupNameProperty]] to:vc];
	[self _appendLine:@"END:VCARD" to:vc];
	return [vc dataUsingEncoding:NSUTF8StringEncoding];
#endif
}
#endif

- (NSString *) description; { return [NSString stringWithFormat:@"ABPerson uid=%@", [self uniqueId]]; }

- (void) encodeWithCoder:(id)aCoder
{
	[super encodeWithCoder:aCoder];
	[aCoder encodeObject: parentgroups];
}

- (id) initWithCoder:(id)aDecoder
{
	self=[super initWithCoder:aDecoder];
	parentgroups = [[aDecoder decodeObject] retain];
	return self;
}

@end
