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

#import "ContactsServiceViewController.h"
#import "SDKManager.h"
#import "ContactDetailsScreenViewController.h"
#import "ContactSearchViewController.h"

@interface ContactsServiceViewController ()

@property (nonatomic, weak) CSContactService *contactService;

@end

@implementation ContactsServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactServiceStatusChanged:) name:kContactServiceAvailabilityChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshContactList:) name:kRefreshContactListNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactListUpdated:) name:kContactListUpdatedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactListUpdated:) name:kContactPresenceUpdatedNotification object:nil];
    
    // Change window background to white
    self.view.wantsLayer = YES;
    self.view.layer.backgroundColor = [NSColor whiteColor].CGColor;
    
    self.contactService = nil;
    for (CSUser *user in [SDKManager getInstance].users) {
        
        if (user.contactService) {
            
            self.contactService = user.contactService;
            break;
        }
    }
    
    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.addContactBtnLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.addContactBtnLabel.attributedTitle = formattedTitle;
    
    self.addContactBtnLabel.enabled = self.contactService.addContactCapability.allowed;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kContactServiceAvailabilityChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kRefreshContactListNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kContactListUpdatedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kContactPresenceUpdatedNotification object:nil];
}

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

- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    
    
    if([segue.identifier isEqualToString:@"showContactDetails"]) {
        
        ContactDetailsScreenViewController *vc = (ContactDetailsScreenViewController *)segue.destinationController;
        NSLog(@"%s Perform Contact Details Screen segue", __PRETTY_FUNCTION__);
        NSLog(@"%s selected Contact = [%@]", __PRETTY_FUNCTION__, self.selectedContact);
        vc.contact = self.selectedContact;
    } else if([segue.identifier isEqualToString:@"contactSearchSegue"]) {
        
        ContactSearchViewController *vc = (ContactSearchViewController *)segue.destinationController;
        NSLog(@"%s Perform Contact Search Screen segue", __PRETTY_FUNCTION__);
        NSLog(@"%s CSContactService = [%@]", __PRETTY_FUNCTION__, self.contactService);
        vc.contactService = self.contactService;
    }
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    
    NSLog(@"%s Number of contacts: [%lu]", __PRETTY_FUNCTION__, [SDKManager getInstance].contacts.count);
    return [SDKManager getInstance].contacts.count;
}

- (NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    NSArray *contactList = [SDKManager getInstance].contacts;
    
    CSContact *contact = contactList[row];
    
    NSTableCellView *cellView = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
    
    NSImage * statusImage;
    if ([tableColumn.identifier isEqualToString:@"contactName"]) {
        
        // first column (Contact Name)
        cellView.textField.stringValue = [NSString stringWithFormat:@"%@", contact];
        
        switch(contact.presence.overallState) {
                
            case CSPresenceStateAvailable:
                statusImage = [NSImage imageNamed:@"available.png"];
                break;
            case CSPresenceStateAway:
                statusImage = [NSImage imageNamed:@"away.png"];
                break;
            case CSPresenceStateBusy:
                statusImage = [NSImage imageNamed:@"busy.png"];
                break;
            case CSPresenceStateDoNotDisturb:
                statusImage = [NSImage imageNamed:@"dnd.png"];
                break;
            case CSPresenceStateOffline:
                statusImage = [NSImage imageNamed:@"offline.png"];
                break;
            case CSPresenceStateOnACall:
                statusImage = [NSImage imageNamed:@"onacall.png"];
                break;
            case CSPresenceStateOutOfOffice:
                statusImage = [NSImage imageNamed:@"outofoffice.png"];
                break;
            case CSPresenceStateUnknown:
                statusImage = [NSImage imageNamed:@"unavailable.png"];
                break;
            case CSPresenceStateUnspecified:
            default:
                statusImage = [NSImage imageNamed:@"default.png"];
                break;
        }
        NSLog(@"%s status: [%@]", __PRETTY_FUNCTION__, statusImage.name);
        cellView.imageView.image = statusImage;
    }
    
    return cellView;
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification {
    
    NSTableView *tb = notification.object;
    
    NSLog(@"%s selected row: [%lu]", __PRETTY_FUNCTION__, (long)tb.selectedRow + 1);
    self.selectedContact = [SDKManager getInstance].contacts[tb.selectedRow];
    NSLog(@"%s contact:[%@]", __PRETTY_FUNCTION__, self.selectedContact);
    [self performSegueWithIdentifier:@"showContactDetails" sender:self];
}

- (void)contactServiceStatusChanged:(NSNotification *)notification {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    CSContactService *contactService = nil;
    for (CSUser *user in [SDKManager getInstance].users) {
        if (user.contactService) {
            contactService = user.contactService;
            break;
        }
    }
    
    self.addContactBtnLabel.enabled = contactService.addContactCapability.allowed;
}

- (void)contactListUpdated:(NSNotification *)notification {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSLog(@"%s contactList: [%@]", __PRETTY_FUNCTION__, self.contactList);
    [self.contactList reloadData];
}

- (void)refreshContactList:(NSNotification *)notification {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    if (![[SDKManager getInstance].contactsRetrievalWatcher isCancelled]) {
        [[SDKManager getInstance].contactsRetrievalWatcher cancel];
    }
    CSContactService *contactService = nil;
    for (CSUser *user in [SDKManager getInstance].users) {
        if (user.contactService) {
            contactService = user.contactService;
            break;
        }
    }
    [contactService retrieveContactsForSource:CSContactSourceTypeAll watcher:[SDKManager getInstance].contactsRetrievalWatcher];
}

@end
