/******************************************************************************/
/*                                                                            */
/* Copyright Avaya LLC.                                                       */
/*                                                                            */
/******************************************************************************/

#import "ContactDetailsScreenViewController.h"
#import "NotificationHelper.h"

@interface ContactDetailsScreenViewController ()

@property (nonatomic, weak) NSString *firstNameBeforeEditing;
@property (nonatomic, weak) NSString *lastNameBeforeEditing;
@property (nonatomic, weak) NSString *workNumberBeforeEditing;
@property (nonatomic, weak) NSString *workEmailBeforeEditing;

@end

@implementation ContactDetailsScreenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Change window background to white
    self.view.wantsLayer = YES;
    self.view.layer.backgroundColor = [NSColor whiteColor].CGColor;
    
    NSColor *color = [NSColor blueColor];
    NSMutableAttributedString *formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.backBtnLabel.attributedTitle];
    NSRange titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.backBtnLabel.attributedTitle = formattedTitle;
    
    formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.editBtnLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.editBtnLabel.attributedTitle = formattedTitle;
    
    formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.deleteBtnLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.deleteBtnLabel.attributedTitle = formattedTitle;
    
    // Check if we can edit this contact
    self.editBtnLabel.enabled = self.contact.updateCapability.allowed;
    
    // Check if we can delete this contact
    self.deleteBtnLabel.enabled = self.contact.deleteCapability.allowed;
    
    self.firstName.stringValue = self.contact.firstName.fieldValue;
    self.lastName.stringValue = self.contact.lastName.fieldValue;
    
    // Check if contact has phone number
    if (self.contact.phoneNumbers.values.count > 0) {
        
        self.workNumber.stringValue = [[self.contact.phoneNumbers.values firstObject] phoneNumber];
    } else {
        
        self.workNumber.stringValue = @"";
    }
    
    // Check if contact has phone number
    if (self.contact.emailAddresses.values.count > 0) {
        
        self.workEmail.stringValue = [(CSContactEmailAddressField *)[self.contact.emailAddresses.values firstObject] address];
    } else {
        
        self.workEmail.stringValue = @"";
    }
    
    self.firstName.delegate = self;
    self.lastName.delegate = self;
    self.workNumber.delegate = self;
    self.workEmail.delegate = self;
}

- (IBAction)backBtn:(id)sender {
    
    [self dismissController:self];
}

- (IBAction)editBtn:(id)sender {
    
    if ([self.editBtnLabel.title isEqualToString:@"EDIT"]) {
        
        // Change button label to 'Save'
        self.editBtnLabel.title = @"SAVE";
        NSColor *color = [NSColor blueColor];
        NSMutableAttributedString *formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.editBtnLabel.attributedTitle];
        NSRange titleRange = NSMakeRange(0,formattedTitle.length);
        [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
        self.editBtnLabel.attributedTitle = formattedTitle;
        self.editBtnLabel.enabled = NO;
        
        // Enable UITextFields for editing
        self.firstName.enabled = YES;
        self.lastName.enabled = YES;
        self.workNumber.enabled = YES;
        self.workEmail.enabled = YES;
        
        self.firstNameBeforeEditing = self.firstName.stringValue;
        self.lastNameBeforeEditing = self.lastName.stringValue;
        self.workNumberBeforeEditing = self.workNumber.stringValue;
        self.workEmailBeforeEditing = self.workEmail.stringValue;
        
    } else if ([self.editBtnLabel.title isEqualToString:@"SAVE"]) {
        
        CSContactService *contactService = nil;
        for (CSUser *user in [SDKManager getInstance].users) {
            
            if (user.contactService) {
                
                contactService = user.contactService;
                break;
            }
        }
        
        CSEditableContact *editedContact = [contactService createEditableContactFromContact:self.contact];
        
        editedContact.firstName.fieldValue = self.firstName.stringValue;
        editedContact.lastName.fieldValue = self.lastName.stringValue;
        
        CSEditableContactEmailAddressField *emailField = [CSEditableContactEmailAddressField new];
        emailField.emailAddressType = CSContactEmailAddressTypeWork;
        emailField.address = self.workEmail.stringValue;
        
        // Check if work-email was updated in edit operation
        if(!self.contact.emailAddresses.values.count){
            [editedContact.emailAddresses addItem:emailField];
            
        }else{
            for (CSContactEmailAddressField *email in self.contact.emailAddresses.values) {
                
                if (email.type == CSContactEmailAddressTypeWork) {
                    
                    if (![email.address isEqualToString:self.workEmail.stringValue]) {
                        [editedContact.emailAddresses removeItem:(CSEditableContactEmailAddressField *)email];
                        [editedContact.emailAddresses addItem:emailField];
                        break;
                    }
                }
            }
        }
        
        // Check if work-phone was updated in edit operation
        for (CSContactPhoneField *phone in self.contact.phoneNumbers.values) {
            
            if (phone.type == CSContactPhoneNumberTypeWork) {
                
                if (![phone.phoneNumber isEqualToString:self.workNumber.stringValue]) {
                    
                    CSEditableContactPhoneField *phoneField = [CSEditableContactPhoneField new];
                    phoneField.phoneNumber = self.workNumber.stringValue;
                    phoneField.defaultPhoneNumber = YES;
                    phoneField.phoneNumberType = CSContactPhoneNumberTypeWork;
                    editedContact.phoneNumbers.values = @[phoneField];
                    break;
                }
            }
        }
        
        [contactService updateContact:editedContact completionHandler:^(CSContact *contact, NSError *error) {
            
            if (error) {
                
                NSLog(@"%s Error while updating contact. Error code [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while updating contact. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG:__PRETTY_FUNCTION__];
            } else {
                
                NSLog(@"%s Contact updated successfully, contact [%@]", __PRETTY_FUNCTION__, contact);
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshContactListNotification object:nil];
            }
        }];
        
        [self dismissController:self];
    }
}

- (IBAction)deleteBtn:(id)sender {
    
    // Delete contact from local storage and server
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    CSContactService *contactService = nil;
    for (CSUser *user in [SDKManager getInstance].users) {
        
        if (user.contactService) {
            
            contactService = user.contactService;
            break;
        }
    }
    
    [contactService deleteContact:self.contact completionHandler:^(NSError *error) {
        
        if (error) {
            
            NSLog(@"%s Error while deleting contact. Error code [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while deleting contact. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG:__PRETTY_FUNCTION__];
        } else {
            
            NSLog(@"%s Contact deleted successfully", __PRETTY_FUNCTION__);
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshContactListNotification object:nil];
        }
    }];
    
    [self dismissController:self];
}

- (void)controlTextDidChange:(NSNotification *)obj {
    
    // Enable Save button only contact was edited
    if ([self.firstName.stringValue isEqualToString:self.firstNameBeforeEditing] &&
        [self.lastName.stringValue isEqualToString:self.lastNameBeforeEditing] &&
        [self.workNumber.stringValue isEqualToString:self.workNumberBeforeEditing] &&
        [self.workEmail.stringValue isEqualToString:self.workEmailBeforeEditing]) {
        
        self.editBtnLabel.enabled = NO;
    } else {
        
        self.editBtnLabel.enabled = YES;
    }
}
@end
