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

#import "MessagingServiceConversationMediaViewController.h"
#import "NotificationHelper.h"
#import "MessagingServiceConversationMediaOperationViewController.h"

@interface MessagingServiceConversationMediaViewController ()

@property (nonatomic, weak) CSMessagingAttachment *selectedAttachment;
@property (nonatomic, weak) CSDataRetrievalWatcher* conversationMessageWatcher;

@end

@implementation MessagingServiceConversationMediaViewController

- (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;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(attachmentReceived:) name:kAttachmentReceivedNotification object:nil];
    
    self.conversationMessageWatcher = [[SDKManager getInstance].messagingServiceManager messagesWatcherForConversationId:self.selectedConversation.conversationId];
    [self.conversationMessageWatcher addDelegate:[SDKManager getInstance].messagingServiceManager];
    
    [self.selectedConversation retrieveMessagesWithWatcher:self.conversationMessageWatcher];
}

- (void) dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kAttachmentReceivedNotification object:nil];
    [self.conversationMessageWatcher addDelegate:nil];
    self.conversationMessageWatcher = nil;
}

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

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    
    NSLog(@"%s Number of attachments in conversation: %lu", __PRETTY_FUNCTION__, (unsigned long)self.selectedConversation.attachmentCount);
    return self.selectedConversation.attachmentCount;
}

- (NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    
    NSMutableArray *mediaItems = [[NSMutableArray alloc] init];
    
    for (CSMessage *msg in self.conversationMessageWatcher.snapshot) {
        
        for (CSMessagingAttachment *attachment in msg.attachments) {
            
            if (attachment.isThumbnail) {
                
                continue;
            } else {
                
                NSLog(@"%s attachmentName: [%@]", __PRETTY_FUNCTION__, attachment.name);
                [mediaItems addObject:attachment];
            }
        }
    }
    
    CSMessagingAttachment *item = mediaItems[row];
    
    NSTableCellView *cellView = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
    
    if ([tableColumn.identifier isEqualToString:@"attachmentName"]) {
        
        cellView.textField.stringValue = item.name;
    } else if ([tableColumn.identifier isEqualToString:@"attachmentStatus"]) {
        
        NSString *status = @"";
        
        switch (item.status) {
            case CSMessagingAttachmentStatusDraft:
                status = @"Draft";
                break;
            case CSMessagingAttachmentStatusOpened:
                status = @"Opened";
                break;
            case CSMessagingAttachmentStatusSending:
                status = @"Sending";
                break;
            case CSMessagingAttachmentStatusDraftError:
                status = @"DraftError";
                break;
            case CSMessagingAttachmentStatusDownloading:
                status = @"Downloading";
                break;
            case CSMessagingAttachmentStatusReadyToOpen:
                status = @"ReadyToOpen";
                break;
            case CSMessagingAttachmentStatusReadyToDownload:
                status = @"ReadyToDownload";
                break;
            case CSMessagingAttachmentStatusDraftRemoving:
                status = @"DraftRemoving";
                break;
            default:
                break;
        }
        cellView.textField.stringValue = status;
    }
    return cellView;
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification {
    
    NSTableView *tb = notification.object;
    
    if (tb.selectedRow >= 0) {
        
        NSLog(@"%s selected row: [%lu]", __PRETTY_FUNCTION__, (long)tb.selectedRow + 1);
        NSMutableArray *mediaItems = [[NSMutableArray alloc] init];
        
        for (CSMessage *msg in self.conversationMessageWatcher.snapshot) {
            
            for (CSMessagingAttachment *attachment in msg.attachments) {
                
                if (attachment.isThumbnail) {
                    
                    continue;
                } else {
                    
                    [mediaItems addObject:attachment];
                }
            }
        }
        self.selectedAttachment = mediaItems[tb.selectedRow];
        NSLog(@"%s selected attachment: [%@]", __PRETTY_FUNCTION__, self.selectedAttachment.name);
        [self performSegueWithIdentifier:@"showContactDetails" sender:self];
    }
}

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

- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    
    MessagingServiceConversationMediaOperationViewController *vc = (MessagingServiceConversationMediaOperationViewController *)segue.destinationController;
    if([segue.identifier isEqualToString:@"mediaOperation"]) {
        
        NSLog(@"%s Perform Media Operation Screen segue", __PRETTY_FUNCTION__);
        NSLog(@"%s selected Attachment = [%@]", __PRETTY_FUNCTION__, self.selectedAttachment);
        vc.selectedAttachment = self.selectedAttachment;
    }
}

@end
