//
//  RootViewController.m
//  AddressBook
//
//  Created by Bill Dudney on 1/2/09.
//  Copyright Gala Factory Software LLC 2009. All rights reserved.
//

#import "RootViewController.h"
#import "ContactsAppDelegate.h"


@implementation RootViewController

@synthesize contactNames;
@synthesize contactIDs;

//START:code.RVC.contactNames
-(NSMutableArray *)contactNames {
  if(nil == contactNames) {
    contactNames = [[NSMutableArray alloc] init];
  }
  return contactNames;
}
//END:code.RVC.contactNames

-(NSMutableArray *)contactIDs {
  if(nil == contactIDs) {
    contactIDs = [[NSMutableArray alloc] init];
  }
  return contactIDs;
}

#pragma mark People Picker Delegate Methods
//START:code.RVC.didCancel
- (void)peoplePickerNavigationControllerDidCancel:
(ABPeoplePickerNavigationController *)peoplePicker {
  [peoplePicker dismissModalViewControllerAnimated:YES];
  [peoplePicker autorelease];
}
//END:code.RVC.didCancel

//START:code.RVC.shouldContinue
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker 
      shouldContinueAfterSelectingPerson:(ABRecordRef)person {
  NSString *name = (NSString *)ABRecordCopyCompositeName(person);
  [self.contactNames addObject:name];
  [self.contactIDs addObject:
   [NSNumber numberWithInt:ABRecordGetRecordID(person)]];
  [peoplePicker dismissModalViewControllerAnimated:YES];
  [peoplePicker autorelease];
  NSIndexPath *path = [NSIndexPath indexPathForRow:self.contactIDs.count - 1 
                                         inSection:0];
  [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path]
                        withRowAnimation:UITableViewRowAnimationRight];
  return NO;
}
//END:code.RVC.shouldContinue

//START:code.RVC.shouldContinuePropertyIdentifier
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker 
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier{
  return NO;
}
//END:code.RVC.shouldContinuePropertyIdentifier

#pragma mark Person VC Method

//START:code.RVC.shouldPerformDefaultActionForPerson
- (BOOL)personViewController:(ABPersonViewController *)personViewController 
                     shouldPerformDefaultActionForPerson:(ABRecordRef)person
                    property:(ABPropertyID)property
                  identifier:(ABMultiValueIdentifier)valueID {
  ABPropertyType type = ABPersonGetTypeOfProperty(property);
  switch (type) {
    case kABStringPropertyType: {
      NSString *value = (NSString *)ABRecordCopyValue(person, property);
      NSLog(@"property value = %@", value);
      [value release];
      break;
    }
    case kABMultiStringPropertyType: {
      ABMutableMultiValueRef multi = ABRecordCopyValue(person, property);
      CFIndex index = ABMultiValueGetIndexForIdentifier(multi, valueID);
      CFStringRef value = ABMultiValueCopyValueAtIndex(multi, index);
      NSLog(@"value = %@", (NSString *)value);
      CFRelease(multi);
      CFRelease(value);
      break;
    }
    default:
      break;
  }
  [self.navigationController popViewControllerAnimated:YES];
  return NO;
}
//END:code.RVC.shouldPerformDefaultActionForPerson

//START:code.RVC.viewDidLoad
- (void)viewDidLoad {
  [super viewDidLoad];
  self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] 
      initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                             target:self
                                             action:@selector(add)]
                                            autorelease];
  self.title = @"Selected Contacts";
}
//END:code.RVC.viewDidLoad

//START:code.RVC.add
- (void)add {
  ABPeoplePickerNavigationController *peoplePicker = 
    [[ABPeoplePickerNavigationController alloc] init];
  peoplePicker.peoplePickerDelegate = self;
  [self presentModalViewController:peoplePicker animated:YES];
}
//END:code.RVC.add

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.contactNames.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  static NSString *CellIdentifier = @"Cell";
  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero 
                                   reuseIdentifier:CellIdentifier] 
            autorelease];
  }
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  cell.textLabel.text = [self.contactNames objectAtIndex:indexPath.row];
  return cell;
}


//START:code.RVC.didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  ABAddressBookRef addressBook = ABAddressBookCreate();
  ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, 
                  [[self.contactIDs objectAtIndex:indexPath.row] intValue]);
  ABPersonViewController *pvc = [[ABPersonViewController alloc] init];
  pvc.personViewDelegate = self;
  pvc.displayedPerson = person;
  [self.navigationController pushViewController:pvc animated:YES];
  CFRelease(addressBook);
  [pvc autorelease];
}
//END:code.RVC.didSelectRowAtIndexPath

//START:code.RVC.makeNewEntry
- (IBAction)makeNewEntry {
  //START:code.RVC.makeAddressBookAndPerson
  ABAddressBookRef addressBook = ABAddressBookCreate();
  ABRecordRef person = ABPersonCreate();
  CFErrorRef error = NULL;
  //END:code.RVC.makeAddressBookAndPerson

  //START:code.RVC.setName
  // set the first and last name properties
  ABRecordSetValue(person, kABPersonFirstNameProperty,
                   CFSTR("Wonder"), &error);
  ABRecordSetValue(person, kABPersonLastNameProperty,
                   CFSTR("Widget"), &error);
  if(NULL != error) {
    NSLog(@"an error occurred");
  }
  //END:code.RVC.setName
  
  //START:code.RVC.setPhoneNum
  // set a phone number
  ABMutableMultiValueRef multi = 
    ABMultiValueCreateMutable(kABMultiStringPropertyType);
  ABMultiValueAddValueAndLabel(multi, CFSTR("(123) 456-7654"), 
                               kABPersonPhoneMobileLabel, NULL);
  ABMultiValueAddValueAndLabel(multi, CFSTR("(321) 543-7890"), 
                               kABPersonPhoneWorkFAXLabel, NULL);
  
  // add the phone numbers to the person record
  ABRecordSetValue(person, kABPersonPhoneProperty, multi, &error);
  CFRelease(multi);
  if(NULL != error) {
    NSLog(@"an error occurred");
  }
  //END:code.RVC.setPhoneNum
  
  //START:code.RVC.setAddress
  // set the home address
  CFStringRef keys[4] = {kABPersonAddressStreetKey, 
                         kABPersonAddressCityKey, 
                         kABPersonAddressStateKey, 
                         kABPersonAddressZIPKey};
  CFStringRef values[4] = {CFSTR("765 Four St."),
                           CFSTR("Fivesville"),
                           CFSTR("CO"),
                           CFSTR("80424")};
  CFDictionaryRef data = 
    CFDictionaryCreate(NULL,
                       (void *)keys,
                       (void *)values,
                       4,
                       &kCFCopyStringDictionaryKeyCallBacks, 
                       &kCFTypeDictionaryValueCallBacks);
  multi = ABMultiValueCreateMutable(kABDictionaryPropertyType);
  ABMultiValueAddValueAndLabel(multi, data, kABHomeLabel, NULL);
  CFRelease(data);
	
  // add the address to the person record
  ABRecordSetValue(person, kABPersonAddressProperty, multi, &error);
  CFRelease(multi);
  //END:code.RVC.setAddress
  
  //START:code.RVC.addPersonAndSaveAndCleanup
  // add the person record, save and clean up
  ABAddressBookAddRecord(addressBook, person, &error);
  ABAddressBookSave(addressBook, &error);
  CFRelease(person);
  CFRelease(addressBook);
  //END:code.RVC.addPersonAndSaveAndCleanup
}
//END:code.RVC.makeNewEntry

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
  // Release anything that's not essential, such as cached data
}

- (void)dealloc {
  self.contactNames = nil;
  self.contactIDs = nil;
  [super dealloc];
}


@end

