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

#import "MessagingServiceConversationViewController.h"
#import "SDKManager.h"
#import "MessagingServiceConversationMediaViewController.h"
#import "NotificationHelper.h"

@interface MessagingServiceConversationViewController ()

@property (nonatomic, weak) CSDataRetrievalWatcher* conversationMessageWatcher;
@property (nonatomic, weak) CSMessage* message;
@property (nonatomic) BOOL typingReported;
@property (nonatomic) BOOL fileAttached;
@property (nonatomic, strong) NSURL *fileToBeAttached;

@end

@implementation MessagingServiceConversationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"%s selected conversation: [%@]", __PRETTY_FUNCTION__, self.selectedConversation);
    
    self.typingReported = NO;
    self.fileAttached = NO;
    self.fileToBeAttached = nil;
    
    // 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.sendBtnLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.sendBtnLabel.attributedTitle = formattedTitle;
    
    formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.leaveBtnLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.leaveBtnLabel.attributedTitle = formattedTitle;
    
    formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.conversationMediaLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.conversationMediaLabel.attributedTitle = formattedTitle;
    
    formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.attachMediaLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.attachMediaLabel.attributedTitle = formattedTitle;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshConversation:) name:kRefreshConversationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(participantTyping:) name:kParticipantTypingNotification object:nil];
    
    // Set title of screen to list of participant(s) in the conversation
    NSString *list = @"";
    for (CSParticipant* participant in self.selectedConversation.allParticipants) {
        
        if ([participant.address isEqualToString:[[SDKManager getInstance].users.firstObject messagingService].selfAddress]) {
            
            // Do not display self address in participant list
            continue;
        } else {
            
            list = [list stringByAppendingString: [NSString stringWithFormat:@"%@ ", participant.displayName]];
        }
    }
    self.participantNameLabel.title = list;
    
    self.conversationMessageWatcher = [[SDKManager getInstance].messagingServiceManager messagesWatcherForConversationId:self.selectedConversation.conversationId];
    [self.conversationMessageWatcher addDelegate:[SDKManager getInstance].messagingServiceManager];
    
    [self.selectedConversation retrieveMessagesWithWatcher:self.conversationMessageWatcher];
    
    self.conversationMessages.stringValue = @"";
    
    [self refreshConversation:nil];
    
    // Add delegate on text field to report isTyping
    //[self.chatMessage setDelegate:self];
}

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

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

- (IBAction)sendBtn:(id)sender {
    
    CSMessage *msg = [self.selectedConversation createMessage];
    __block CSMessage *messageToSend = msg;
    [msg setBodyAndReportTyping:self.chatMessage.stringValue completionHandler:^(NSError *error) {
        
        if (error) {
            
            NSLog(@"%s Cannot create message. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Cannot create message. Error code [%ld] - %@", (long)error.code, error.localizedDescription]  TAG: __PRETTY_FUNCTION__];
        } else {
            
            NSLog(@"%s message created successfully", __PRETTY_FUNCTION__);
            
            if (self.fileAttached) {
                
                CSMessagingAttachment *attachment = [messageToSend createAttachment];
                
                if (attachment) {
                    
                    NSLog(@"%s Attach file to message", __PRETTY_FUNCTION__);
                    [attachment setName:[self.fileToBeAttached lastPathComponent] completionHandler:^(NSError *error) {
                        
                        if (error) {
                            
                            NSLog(@"%s Error while setting name of attachment. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while setting name of attachment. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG: __PRETTY_FUNCTION__];
                        } else {
                            
                            NSLog(@"%s Successfully set name of attachment", __PRETTY_FUNCTION__);
                        }
                    }];
                    
                    [attachment setIsThumbnail:NO completionHandler:^(NSError *error) {
                        
                        if (error) {
                            
                            NSLog(@"%s Error while setting 'IsThumbnail' attribute of attachment. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while setting 'IsThumbnail' attribute of attachment. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG: __PRETTY_FUNCTION__];
                        } else {
                            
                            NSLog(@"%s Successfully set 'IsThumbnail' attribute of attachment", __PRETTY_FUNCTION__);
                        }
                    }];
                    
                    [attachment setIsGeneratedContent:NO completionHandler:^(NSError *error) {
                        
                        if (error) {
                            
                            NSLog(@"%s Error while setting 'IsGeneratedContent' attribute of attachment. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while setting 'IsGeneratedContent' attribute of attachment. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG: __PRETTY_FUNCTION__];
                        } else {
                            
                            NSLog(@"%s Successfully set 'IsGeneratedContent' attribute of attachment", __PRETTY_FUNCTION__);
                        }
                    }];
                    
                    [attachment setLocation: [NSString stringWithFormat:@"%@", self.fileToBeAttached.path] completionHandler:^(NSError *error) {
                        
                        if (error) {
                            
                            NSLog(@"%s Error while setting location of attachment. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while setting name of attachment. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG: __PRETTY_FUNCTION__];
                        } else {
                            
                            NSLog(@"%s Successfully set location of attachment", __PRETTY_FUNCTION__);
                        }
                    }];
                    
                    [attachment setMimeType:@"*/*" completionHandler:^(NSError *error) {
                        
                        if (error) {
                            
                            NSLog(@"%s Error while setting mime type of attachment. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while setting mime type of attachment. Error code [%ld] - %@", (long)error.code, error.localizedDescription] TAG: __PRETTY_FUNCTION__];
                        } else {
                            
                            NSLog(@"%s Successfully set mime type of attachment", __PRETTY_FUNCTION__);
                        }
                    }];
                } else {
                    
                    NSLog(@"%s Error while creating attachment", __PRETTY_FUNCTION__);
                    [NotificationHelper displayMessageToUser: @"Error while creating attachment" TAG: __PRETTY_FUNCTION__];
                }
                self.fileAttached = NO;
                self.fileToBeAttached = nil;
            } else {
                
                NSLog(@"%s no attachment with this message", __PRETTY_FUNCTION__);
            }
            
            [messageToSend sendWithCompletionHandler:^(NSError *error) {
                
                if (error) {
                    
                    NSLog(@"%s Cannot send message. Error [%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                    [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Cannot send message. Error code [%ld] - %@", (long)error.code, error.localizedDescription]  TAG: __PRETTY_FUNCTION__];
                } else {
                    
                    NSLog(@"%s message sent successfully", __PRETTY_FUNCTION__);
                    self.chatMessage.stringValue = @"";
                }
            }];
        }
    }];
}

- (IBAction)leaveBtn:(id)sender {
    
    [self.selectedConversation leaveWithCompletionHandler:^(NSError *error) {
        
        if (error) {
            
            NSLog(@"%s Error while leaving conversation. Error [%ld] - %@", __PRETTY_FUNCTION__, error.code, error.localizedDescription);
            [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while leaving conversation. Error code [%ld] - %@", (long)error.code, error.localizedDescription]  TAG: __PRETTY_FUNCTION__];
        } else {
            
            NSLog(@"%s Successfully left the conversation", __PRETTY_FUNCTION__);
        }
    }];
    [self dismissController:self];
}

- (IBAction)attachMediaBtn:(id)sender {
    
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    openDlg.canChooseFiles = YES;
    openDlg.canCreateDirectories = NO;
    
    // Display the dialog. If OK is pressed process the files
    if([openDlg runModal] == NSModalResponseOK) {
        
        self.fileToBeAttached = [openDlg URL];
        NSLog(@"%s Name of selected file, name: [%@], path: [%@]", __FUNCTION__, [self.fileToBeAttached lastPathComponent], self.fileToBeAttached.path);
        self.fileAttached = YES;
        self.chatMessage.stringValue = [NSString stringWithFormat:@"attachment: [%@]", [self.fileToBeAttached lastPathComponent]];
    }
}

- (void)controlTextDidChange:(NSNotification *)obj {
    
    if (self.selectedConversation.createMessageCapability.allowed) {
        
        if (!self.typingReported) {
            
            CSMessage *msg2 = [self.selectedConversation createMessage];
            if (self.chatMessage.stringValue.length > 0) {
                
                NSLog(@"%s typing...", __PRETTY_FUNCTION__);
                [msg2 reportTyping:YES];
                self.typingReported = YES;
                [self.selectedConversation removeMessage:msg2 completionHandler:^(NSError *error) {
                    
                    if (error) {
                        
                        NSLog(@"%s Error while removing message. Error[%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                        [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while removing message. Error code [%ld] - %@", (long)error.code, error.localizedDescription]  TAG: __PRETTY_FUNCTION__];
                    } else {
                        
                        NSLog(@"%s Message deleted successfully", __PRETTY_FUNCTION__);
                    }
                }];
            } else {
                
            }
        } else {
            
            CSMessage *msg2 = [self.selectedConversation createMessage];
            
            NSLog(@"%s not typing...", __PRETTY_FUNCTION__);
            [msg2 reportTyping:NO];
            self.typingReported = NO;
            [self.selectedConversation removeMessage:msg2 completionHandler:^(NSError *error) {
                
                if (error) {
                    
                    NSLog(@"%s Error while removing message. Error[%ld] - %@", __PRETTY_FUNCTION__, (long)error.code, error.localizedDescription);
                    [NotificationHelper displayMessageToUser: [NSString stringWithFormat:@"Error while removing message. Error code [%ld] - %@", (long)error.code, error.localizedDescription]  TAG: __PRETTY_FUNCTION__];
                } else {
                    
                    NSLog(@"%s Message deleted successfully", __PRETTY_FUNCTION__);
                }
            }];
        }
    }
}

- (void)refreshConversation:(NSNotification *)notification {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    self.sendBtnLabel.enabled = self.selectedConversation.createMessageCapability.allowed;
    self.leaveBtnLabel.enabled = self.selectedConversation.leaveCapability.allowed;
    
    [self.selectedConversation retrieveMessagesWithWatcher:self.conversationMessageWatcher];
    
    self.conversationMessages.stringValue = @"";
    
    for (CSMessage *msg in [self.conversationMessageWatcher.snapshot reverseObjectEnumerator]) {
        
        if (msg.fromMe) {
            
            for (CSParticipant* participant in [self.selectedConversation allParticipants]) {
                
                if ([participant.address isEqualToString:[[[SDKManager getInstance] users].firstObject messagingService].selfAddress]) {
                    
                    self.conversationMessages.stringValue = [self.conversationMessages.stringValue stringByAppendingString: [NSString stringWithFormat:@"%@: %@\n", participant.displayName, msg.body]];
                    break;
                }
            }
        } else {
            
            self.conversationMessages.stringValue = [self.conversationMessages.stringValue stringByAppendingString: [NSString stringWithFormat:@"%@: %@\n", msg.fromParticipant.displayName, msg.body]];
        }
        
        if (msg.markAsReadCapability.allowed) {
            
            [msg markAsRead];
        }
    }
}

- (void)participantTyping:(NSNotification *)notification {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    NSString* participantName = notification.object;
    if (participantName.length != 0) {
        
        self.typingParticipantName.hidden = NO;
        self.typingParticipantName.stringValue = [NSString stringWithFormat:@"%@ is typing...", notification.object];
    } else {
        
        self.typingParticipantName.hidden = YES;
        self.typingParticipantName.stringValue = @"";
    }
}

- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    
    MessagingServiceConversationMediaViewController *vc = (MessagingServiceConversationMediaViewController *)segue.destinationController;
    if([segue.identifier isEqualToString:@"openConversationMedia"]) {
        
        NSLog(@"%s Perform Open Conversation Media Screen segue", __PRETTY_FUNCTION__);
        NSLog(@"%s selected Conversation = [%@]", __PRETTY_FUNCTION__, self.selectedConversation);
        vc.selectedConversation = self.selectedConversation;
    }
}

@end
