//
//  Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController.m
//  Retrieving and Setting a Person’s Address Book Image
//
//  Created by Vandad Nahavandipoor on 21/07/2011.
//  Copyright 2011 Pixolity Ltd. All rights reserved.
//

#import "Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController.h"

@implementation 
  Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController

@synthesize labelOldImage;
@synthesize imageViewOld;
@synthesize labelNewImage;
@synthesize imageViewNew;

- (UIImage *) getPersonImage:(ABRecordRef)paramPerson{
  
  UIImage *result = nil;
  
  if (paramPerson == NULL){
    NSLog(@"Kontakt ma wartość nil.");
    return NULL;
  }
  
  NSData *imageData = (__bridge_transfer NSData *)
                      ABPersonCopyImageData(paramPerson);
  
  if (imageData != nil){
    UIImage *image = [UIImage imageWithData:imageData];
    result = image;
  }
  
  return result;
  
}

- (BOOL) setPersonImage:(ABRecordRef)paramPerson
          inAddressBook:(ABAddressBookRef)paramAddressBook
          withImageData:(NSData *)paramImageData{
  
  BOOL result = NO;
  
  if (paramAddressBook == NULL){
    NSLog(@"Książka adresowa ma wartość nil.");
    return NO;
  }
  
  if (paramPerson == NULL){
    NSLog(@"Kontakt ma wartość nil.");
    return NO;
  }
  
  CFErrorRef couldSetPersonImageError = NULL;
  
  BOOL couldSetPersonImage = 
  ABPersonSetImageData(paramPerson,
                       (__bridge CFDataRef)paramImageData,
                       &couldSetPersonImageError);
  
  if (couldSetPersonImage){
    NSLog(@"Udało się przypisać obraz kontaktowi. Zapis zmian...");
    if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
      BOOL couldSaveAddressBook = NO;
      CFErrorRef couldSaveAddressBookError = NULL;
      couldSaveAddressBook = ABAddressBookSave(paramAddressBook,
                                               &couldSaveAddressBookError);
      if (couldSaveAddressBook){
        NSLog(@"Udało się zapisać zmiany w książce adresowej.");
        result = YES;
      } else {
        NSLog(@"Nie udało się zapisać zmian w książce adresowej.");
      }
    } else {
      NSLog(@"Nie ma żadnych zmian do zapisania!");
    }
  } else {
    NSLog(@"Nie udało się przypisać obrazu kontaktowi.");
  }
  
  return result;
  
}

- (ABRecordRef) newPersonWithFirstName:(NSString *)paramFirstName
                              lastName:(NSString *)paramLastName
                         inAddressBook:(ABAddressBookRef)paramAddressBook{
  
  ABRecordRef result = NULL;
  
  if (paramAddressBook == NULL){
    NSLog(@"Książka adresowa ma wartość NULL.");
    return NULL;
  }
  
  if ([paramFirstName length] == 0 &&
      [paramLastName length] == 0){
    NSLog(@"Nie podano imienia i nazwiska.");
    return NULL;
  }
  
  result = ABPersonCreate();
  
  if (result == NULL){
    NSLog(@"Nie udało się utworzyć nowego kontaktu.");
    return NULL;
  }
  
  BOOL couldSetFirstName = NO;
  BOOL couldSetLastName = NO;
  CFErrorRef setFirstNameError = NULL;
  CFErrorRef setLastNameError = NULL;
  
  couldSetFirstName = ABRecordSetValue(result,
                                       kABPersonFirstNameProperty,
                                       (__bridge CFTypeRef)paramFirstName,
                                       &setFirstNameError);
  
  couldSetLastName = ABRecordSetValue(result,
                                      kABPersonLastNameProperty,
                                      (__bridge CFTypeRef)paramLastName,
                                      &setLastNameError);
  
  CFErrorRef couldAddPersonError = NULL;
  BOOL couldAddPerson = ABAddressBookAddRecord(paramAddressBook,
                                               result,
                                               &couldAddPersonError);
  
  if (couldAddPerson){
    NSLog(@"Udało się dodać nowy kontakt.");
  } else {
    NSLog(@"Nie udało się dodać nowego kontaktu.");
    CFRelease(result);
    result = NULL;
    return result;
  }
  
  if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
    
    CFErrorRef couldSaveAddressBookError = NULL;
    BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, 
                                                  &couldSaveAddressBookError);
    
    if (couldSaveAddressBook){
      NSLog(@"Udało się zapisać zmiany w książce adresowej.");
    } else {
      NSLog(@"Nie udało się zapisać zmian w książce adresowej.");
    }
  }
  
  if (couldSetFirstName &&
      couldSetLastName){
    NSLog(@"Udało się zmienić imię i nazwisko kontaktu w książce adresowej.");
  } else {
    NSLog(@"Nie udało się zmienić imienia i nazwiska kontaktu w książce adresowej.");
  }
  
  return result;
  
}

- (void) changeYPositionOfView:(UIView *)paramView
                            to:(CGFloat)paramY{
  
  CGRect viewFrame = paramView.frame;
  viewFrame.origin.y = paramY;
  paramView.frame = viewFrame;
  
}

- (void) createLabelAndImageViewForOldImage{
  
  self.labelOldImage = [[UILabel alloc] initWithFrame:CGRectZero];
  self.labelOldImage.text = @"Poprzedni obraz";
  self.labelOldImage.font = [UIFont systemFontOfSize:16.0f];
  [self.labelOldImage sizeToFit];
  self.labelOldImage.center = self.view.center;
  [self.view addSubview:self.labelOldImage];
  [self changeYPositionOfView:self.labelOldImage
                           to:80.0f];
  
  self.imageViewOld = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 
                                                                    0.0f, 
                                                                    100.0f,
                                                                    100.0f)];
  self.imageViewOld.center = self.view.center;
  self.imageViewOld.contentMode = UIViewContentModeScaleAspectFit;
  [self.view addSubview:self.imageViewOld];
  [self changeYPositionOfView:self.imageViewOld
                           to:105.0f];
  
}

- (void) createLabelAndImageViewForNewImage{
  
  self.labelNewImage = [[UILabel alloc] initWithFrame:CGRectZero];
  self.labelNewImage.text = @"Nowy obraz";
  self.labelNewImage.font = [UIFont systemFontOfSize:16.0f];
  [self.labelNewImage sizeToFit];
  self.labelNewImage.center = self.view.center;
  [self.view addSubview:self.labelNewImage];
  [self changeYPositionOfView:self.labelNewImage
                           to:210.0f];
  
  self.imageViewNew = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 
                                                                    0.0f, 
                                                                    100.0f,
                                                                    100.0f)];
  self.imageViewNew.center = self.view.center;
  self.imageViewNew.contentMode = UIViewContentModeScaleAspectFit;
  [self.view addSubview:self.imageViewNew];
  [self changeYPositionOfView:self.imageViewNew
                           to:235.0f];
  
}

/* 1 */
//- (void)viewDidLoad{
//  [super viewDidLoad];
//  
//  self.view.backgroundColor = [UIColor whiteColor];
//  [self createLabelAndImageViewForOldImage];
//  [self createLabelAndImageViewForNewImage];
//  
//}

/* 2 */

- (ABRecordRef) getPersonWithFirstName:(NSString *)paramFirstName
                              lastName:(NSString *)paramLastName
                         inAddressBook:(ABRecordRef)paramAddressBook{
  
  ABRecordRef result = NULL;
  
  if (paramAddressBook == NULL){
    NSLog(@"Książka adresowa ma wartość NULL.");
    return NULL;
  }
  
  NSArray *allPeople = (__bridge_transfer NSArray *)
  ABAddressBookCopyArrayOfAllPeople(paramAddressBook);
  
  NSUInteger peopleCounter = 0;
  for (peopleCounter = 0;
       peopleCounter < [allPeople count];
       peopleCounter++){
    
    ABRecordRef person = (__bridge ABRecordRef)
    [allPeople objectAtIndex:peopleCounter];
    
    NSString *firstName = (__bridge_transfer NSString *)
    ABRecordCopyValue(person, kABPersonFirstNameProperty);
    
    NSString *lastName = (__bridge_transfer NSString *)
    ABRecordCopyValue(person, kABPersonLastNameProperty);
    
    BOOL firstNameIsEqual = NO;
    BOOL lastNameIsEqual = NO;
    
    if ([firstName length] == 0 &&
        [paramFirstName length] == 0){
      firstNameIsEqual = YES;
    }
    else if ([firstName isEqualToString:paramFirstName]){
      firstNameIsEqual = YES;
    }
    
    if ([lastName length] == 0 &&
        [paramLastName length] == 0){
      lastNameIsEqual = YES;
    }
    else if ([lastName isEqualToString:paramLastName]){
      lastNameIsEqual = YES;
    }
    
    if (firstNameIsEqual &&
        lastNameIsEqual){
      return person;
    }
    
  }
  
  return result;
  
}

- (void)viewDidLoad{
  [super viewDidLoad];
  
  self.view.backgroundColor = [UIColor whiteColor];
  [self createLabelAndImageViewForOldImage];
  [self createLabelAndImageViewForNewImage];
  
  ABAddressBookRef addressBook = ABAddressBookCreate();
  
  if (addressBook != NULL){
    
    ABRecordRef janKowalski = [self getPersonWithFirstName:@"Jan"
                                                  lastName:@"Kowalski"
                                            inAddressBook:addressBook];
    
    if (janKowalski == NULL){
      NSLog(@"Nie znaleziono rekordu. Tworzenie nowego...");
      janKowalski = [self newPersonWithFirstName:@"Jan"
                                        lastName:@"Kowalski"
                                   inAddressBook:addressBook];
      if (janKowalski == NULL){
        NSLog(@"Nie udało się utworzyć nowego rekordu dla tego kontaktu.");
        CFRelease(addressBook);
        return;
      }
    }
    
    self.imageViewOld.image = [self getPersonImage:janKowalski];
    
    NSString *newImageFilePath = 
    [[NSBundle mainBundle] pathForResource:@"Jan Kowalski"
                                    ofType:@"jpg"];
    
    UIImage *newImage = [[UIImage alloc] 
                         initWithContentsOfFile:newImageFilePath];
    
    NSData *newImageData = UIImagePNGRepresentation(newImage);
    
    if ([self setPersonImage:janKowalski
               inAddressBook:addressBook
               withImageData:newImageData]){
      NSLog(@"Udało się przypisać nowy obraz kontaktowi.");
      self.imageViewNew.image = [self getPersonImage:janKowalski];
    } else {
      NSLog(@"Nie udało się przypisać nowego obrazu kontaktowi.");
    }
    
    CFRelease(janKowalski);
    CFRelease(addressBook);
  }
  
}

- (void)viewDidUnload{
  [super viewDidUnload];
  self.labelOldImage = nil;
  self.imageViewOld = nil;
  self.labelNewImage = nil;
  self.imageViewNew = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation
        :(UIInterfaceOrientation)interfaceOrientation{
  return YES;
}

@end
