//
//  NotifyDataSource.m
//  HWMSDKDemo
//
//

#import "NotifyMessageHandler.h"
#import <HWMUISDK/HWMUISDK.h>
#import "UIUtil.h"
#import "CustomInMeetingUIManager.h"
#import "LoginManager.h"
#import "CommonUtil.h"
#import "DateUtil.h"
#import "GlobalHandlerImpl.h"
@implementation NotifyMessageHandler

+ (instancetype)sharedInstance
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init{
    if (self = [super init]) {
        self.notifyMessages = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)onKickedOut:(NSString *)result{
    [[LoginManager sharedInstance] updateHasLogin:NO];
    [UIUtil showMessage:@"您的账号在其他设备登录，您已被迫下线，请重新登录"];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeKickOut content:result];
        [self msgAddObject:msg];

}
- (void)onLoginError:(NSError *)error {
    if (error) {
        [[LoginManager sharedInstance] updateHasLogin:NO];
        [UIUtil showMessageWithError:error];
        [[HWMSdk getOpenApi] logout:^(NSError * _Nullable error, HWMLogoutResult * _Nullable result) {
        }];
    }
}

/// 会议状态变更通知
/// 可选
/// @param status 会议状态
- (void)onConfStatusChanged:(HWMSDKConfStatus)status{
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeConfStatus content:[NSString stringWithFormat:@"%lu",(unsigned long)status]];
        [self msgAddObject:msg];


}

-(void)onConfEndedNotify:(HWMSDKERR)confEndCode {
    NSMutableString *msgString = [[NSMutableString alloc] init];
    NSString *errorLocalizedString = [[HWMBizSdk getBizOpenApi] getErrorMessage:confEndCode];
    if (errorLocalizedString && errorLocalizedString.length > 0) {
        [msgString appendFormat:@"%@\n", errorLocalizedString];
    }
    [msgString appendFormat:@"错误码:%lu", confEndCode];
    [UIUtil showMessage:msgString];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeConfEnd content:[NSString stringWithFormat:@"%zd", confEndCode]];
    [self msgAddObject:msg];
}

- (void)onP2PConfRecord:(HWMP2PConfRecordInfoModel *)recordInfo {
    NSMutableDictionary *callerDict = [[NSMutableDictionary alloc] init];
    callerDict[@"nickName"] = recordInfo.callerInfo.nickName ?: @"";
    callerDict[@"number"] = recordInfo.callerInfo.number ?: @"";
    callerDict[@"userUuid"] = recordInfo.callerInfo.userUuid ?: @"";
    callerDict[@"thirdUserId"] = recordInfo.callerInfo.thirdUserId ?: @"";
    callerDict[@"extendedField"] = recordInfo.callerInfo.extendedField ?: @"";
    callerDict[@"orgId"] = recordInfo.callerInfo.orgId ?: @"";
    NSMutableDictionary *calleeDict = [[NSMutableDictionary alloc] init];
    calleeDict[@"nickName"] = recordInfo.calleeInfo.nickName ?: @"";
    calleeDict[@"number"] = recordInfo.calleeInfo.number ?: @"";
    calleeDict[@"userUuid"] = recordInfo.calleeInfo.userUuid ?: @"";
    calleeDict[@"thirdUserId"] = recordInfo.calleeInfo.thirdUserId ?: @"";
    calleeDict[@"extendedField"] = recordInfo.calleeInfo.extendedField ?: @"";
    calleeDict[@"orgId"] = recordInfo.calleeInfo.orgId ?: @"";
    NSMutableDictionary *recordDict = [[NSMutableDictionary alloc] init];
    recordDict[@"callerInfo"] = callerDict;
    recordDict[@"calleeInfo"] = calleeDict;
    recordDict[@"startTimeStamp"] = @(recordInfo.startTimeStamp);
    recordDict[@"endTimeStamp"] = @(recordInfo.endTimeStamp);
    recordDict[@"mediaType"] = @(recordInfo.mediaType);
    recordDict[@"isCallOut"] = @(recordInfo.isCallOut);
    recordDict[@"isCallEstablished"] = @(recordInfo.isCallEstablished);
    recordDict[@"resultCode"] = @(recordInfo.resultCode);
    recordDict[@"resultMsg"] = recordInfo.resultMsg ?: @"";
    NSString *content = [CommonUtil convertDictionaryToJson:recordDict];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeP2PConfRecord content:content];
    [self msgAddObject:msg];
}

- (void)onSelfIsChairManChanged:(BOOL)isChairMan{
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeSelfHostRoleChange content:isChairMan?@"YES":@"NO"];
    [self msgAddObject:msg];
}

/// 会议列表变化通知
/// @param confList 会议列表
- (void)onReceiveConfList:(NSArray<HWMConfDetail *> *)confList {
    NSLog(@"confList:%@", confList);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"onReceiveConfList" object:nil];
}

- (void)onRecordPermissionNotify:(BOOL)isHasPermission {
    NSLog(@"onRecordPermissionNotify:%d", isHasPermission);
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeRecordPermission content:isHasPermission?@"YES":@"NO"];
    [self msgAddObject:msg];
}

-(void)onBookConfSmsPermissionNotify:(BOOL)isHasPermission {
    NSLog(@"onBookConfSmsPermissionNotify:%d", isHasPermission);
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeSmsPermission content:isHasPermission?@"YES":@"NO"];
    [self msgAddObject:msg];
}

- (void)onMeetingInfoChanged:(HWMSDKMeetingInfoModel *)meetingInfo {
    NSMutableString *confDetaiContent = [[NSMutableString alloc] init];
    [confDetaiContent appendFormat:@"会议主题：%@，\n", meetingInfo.baseInfo.confSubject];
    [confDetaiContent appendFormat:@"会议开始时间：%@，\n", [DateUtil formatTimeStringWithTimeInterval:meetingInfo.baseInfo.startTimeStamp isHasTimeZoneInterval:NO]];
    [confDetaiContent appendFormat:@"会议结束时间：%@，\n", [DateUtil formatTimeStringWithTimeInterval:meetingInfo.baseInfo.endTimeStamp isHasTimeZoneInterval:NO]];
    [confDetaiContent appendFormat:@"来宾密码：%@，\n", meetingInfo.baseInfo.guestPwd];
    [confDetaiContent appendFormat:@"主席密码：%@，\n", meetingInfo.baseInfo.hostPwd];
    [confDetaiContent appendFormat:@"观众密码：%@，\n", meetingInfo.baseInfo.audiencePwd];
    [confDetaiContent appendFormat:@"会议ID：%@\n", meetingInfo.baseInfo.confId];
    [confDetaiContent appendFormat:@"主席入会链接：%@，\n", meetingInfo.baseInfo.hostJoinUri];
    [confDetaiContent appendFormat:@"来宾入会链接：%@，\n", meetingInfo.baseInfo.guestJoinUri];
    [confDetaiContent appendFormat:@"观众入会链接：%@，\n", meetingInfo.baseInfo.audienceJoinUri];
    [confDetaiContent appendFormat:@"是否视频会议：%d，\n", meetingInfo.baseInfo.mediaType == HWMConfMediaTypeVideo];
    [confDetaiContent appendFormat:@"当前是否是主席：%d，\n", (unsigned long)meetingInfo.baseInfo.selfConfRole == HWMConfRoleHost];
    [confDetaiContent appendFormat:@"自定义信息：%@\n", meetingInfo.baseInfo.openCustomPara];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeConfDetail content:confDetaiContent];
    [self msgAddObject:msg];

}

- (void)onConfIncomingNotify:(HWMSDKConfIncomingInfoModel *)confIncomingInfo {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeConfComing content:[NSString stringWithFormat:@"会议标题：%@\n会议ID:%@\nvmr会议ID:%@\n是否视频会议:%@\nthirdUserId:%@\n预定者:%@\n预定者中文别名:%@\n预定者英文别名:%@\n邀请人extendedField:%@\n企业ID:%@\n", confIncomingInfo.subject, confIncomingInfo.confId, confIncomingInfo.vmrConfId, (confIncomingInfo.confMediaType == HWMConfMediaTypeVideo ? @"YES" : @"NO"), confIncomingInfo.thirdUserId, confIncomingInfo.schedulerName, confIncomingInfo.schedulerAliasCN, confIncomingInfo.schedulerAliasEN, confIncomingInfo.inviteExtendedField, confIncomingInfo.inviteCorpId]];
    [self msgAddObject:msg];
}

- (void)onSelfShareStateChanged:(BOOL)isShare {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeScreenShareStateChange content:isShare ? @"Start" : @"Stop"];
    [self msgAddObject:msg];
}

- (void)onToolBarItemClick:(HWMConfCtrlType)type {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeToolBarItemClick content:[NSString stringWithFormat:@"菜单类型: %ld", type]];
    [self msgAddObject:msg];
}

- (void)onFloatingWindowDidAppear {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeFloatingWindowStateChange content:@"Appear"];
    [self msgAddObject:msg];
}

- (void)onFloatingWindowDidDisappear {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeFloatingWindowStateChange content:@"Disappear"];
    [self msgAddObject:msg];
}

- (void)onAddAttendeeNotify:(HWMSDKAddAttendeeResultListModel *)resultList {
    NSMutableString *content = [[NSMutableString alloc] init];
    [resultList.addAttendeeInfos enumerateObjectsUsingBlock:^(HWMSDKAddAttendeeInfoModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *str = [NSString stringWithFormat:@"number:%@，thirdUserId:%@，result:%ld， extendedField: %@\n", obj.number, obj.thirdUserId, obj.result, obj.extendedField];
        [content appendString:str];
    }];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeAddAttendeeResult content:content];
    [self msgAddObject:msg];
}

- (void)onWaitingListChanged:(NSArray<HWMAttendeeInfo *> *)waitingInfoList {
    NSMutableString *content = [[NSMutableString alloc] init];
    [waitingInfoList enumerateObjectsUsingBlock:^(HWMAttendeeInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *str = [NSString stringWithFormat:@"name:%@，number:%@，thirdUserId:%@，extendedField:%@\n", obj.name, obj.number, obj.thirdUserId, obj.extendedField];
        [content appendString:str];
    }];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeWaitingListChange content:content];
    [self msgAddObject:msg];
}

- (void)onSelfRoleChanged:(HWMConfRole)confRole {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeSelfRoleChange content:[self confRoleString:confRole]];
    [self msgAddObject:msg];
}

- (NSString *)confRoleString:(HWMConfRole)confRole {
    switch (confRole) {
        case HWMConfRoleAttendeee:
            return @"普通与会者";
        case HWMConfRoleHost:
            return @"主持人";
        case HWMConfRoleAudience:
            return @"观众";
        case HWMConfRoleCohost:
            return @"联席主持人";
        default:
            return @"";
    }
}

- (void)onAttendeeListChanged:(NSArray<HWMAttendeeInfo *> *)attendeeList {
    NSMutableString *content = [[NSMutableString alloc] init];
    [attendeeList enumerateObjectsUsingBlock:^(HWMAttendeeInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *str = [NSString stringWithFormat:@"name:%@，number:%@，thirdUserId:%@，extendedField:%@，state:%ld\n", obj.name, obj.number, obj.thirdUserId, obj.extendedField, obj.state];
        [content appendString:str];
    }];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeAttendeeListChange content:content];
    [self msgAddObject:msg];
}

- (HWMWatermarkControlOption)watermarkControlOption {
    return [GlobalHandlerImpl sharedInstance].watermarkControlOption;
}

- (void)onCorpConfigNotify:(HWMCorpConfigInfo *)corpConfig {
    NSString *content = [NSString stringWithFormat:@"enablePstn:%d，enableRecord:%d，corpEnableSummary:%d\n", corpConfig.enablePstn, corpConfig.enableRecord, corpConfig.corpEnableSummary];
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeCorpConfigInfoChange content:content];
    [self msgAddObject:msg];
}

- (void)onSubtitleStateChanged:(BOOL)isOpen {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeSubtitleStateChange content:isOpen ? @"YES" : @"NO"];
    [self msgAddObject:msg];
}

- (void)onWaitingRoomStateChanged:(BOOL)isOpen {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeWaitingRoomStateChange content:isOpen ? @"YES" : @"NO"];
    [self msgAddObject:msg];
}

- (void)onRealTimeSubtitleInfoNotify:(HWMSDKRealTimeSubtitleModel *)realTimeSubtitle {
    NSString *content = [NSString stringWithFormat:@"%@：originalMsg:%@，translatedMsg:%@, beginTime: %ld, endTime: %ld, connectionTime: %ld", realTimeSubtitle.name, realTimeSubtitle.originalMsg, realTimeSubtitle.translatedMsg, realTimeSubtitle.beginTime, realTimeSubtitle.endTime, realTimeSubtitle.connectionTime];
    if (self.subtitleDelegate && [self.subtitleDelegate respondsToSelector:@selector(onRealTimeNotify:)]) {
        [self.subtitleDelegate onRealTimeNotify:content];
    }
}

- (void)onSubtitleRecordNotify:(HWMSDKSubtitleRecordInfoModel *)subtitleInfo {
    NSString *content = [NSString stringWithFormat:@"%@：originalMsg:%@，translatedMsg:%@, beginTime: %ld, endTime: %ld, connectionTime: %ld", subtitleInfo.realTimeSubtitle.name, subtitleInfo.realTimeSubtitle.originalMsg, subtitleInfo.realTimeSubtitle.translatedMsg, subtitleInfo.realTimeSubtitle.beginTime, subtitleInfo.realTimeSubtitle.endTime, subtitleInfo.realTimeSubtitle.connectionTime];
    if (self.subtitleDelegate && [self.subtitleDelegate respondsToSelector:@selector(onRecordNotify:)]) {
        [self.subtitleDelegate onRecordNotify:content];
    }
}

- (void)onUserCorpInfo:(HWMUserCorpInfoNotifyType)type {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeUserCorpConfigChange content:[NSString stringWithFormat:@"%ld", type]];
    [self msgAddObject:msg];
    
    if (type == HWMUserCorpInfoNotifyTypeUserDelete) {
        [[LoginManager sharedInstance] updateHasLogin:NO];
        [UIUtil showMessage:@"账号已注销"];
        [[HWMSdk getOpenApi] logout:^(NSError * _Nullable error, HWMLogoutResult * _Nullable result) {
        }];
    }
}

- (void)onLoginStateChangeNotify:(HWMLoginState)state {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeLoginStateChange content:[self loginStateString:state]];
    [self msgAddObject:msg];
}

- (NSString *)loginStateString:(HWMLoginState)state {
    switch (state) {
        case HWMLoginStateUnLogin:
            return @"未登录";
        case HWMLoginStateLogining:
            return @"登录中";
        case HWMLoginStateLogined:
            return @"已登录";
        case HWMLoginStateLogouting:
            return @"注销中";
    }
}

- (void)onToolBarDidAppear {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeToolBarStateChange content:@"Appear"];
    [self msgAddObject:msg];
}

- (void)onToolBarDidDisappear {
    NotifyMessageModel *msg = [[NotifyMessageModel alloc] initWithMsgType:NotifyMessageModelTypeToolBarStateChange content:@"Disappear"];
    [self msgAddObject:msg];
}

- (void)onAudioFrameNotify:(HWMSDKAudioFrameDataModel *)pFrame {
    if (!pFrame.pBuffer) {
        return;
    }
    
    NSFileHandle *audioFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:[GlobalHandlerImpl sharedInstance].audioFrameDataFile];
    [audioFileHandle seekToEndOfFile];
    [audioFileHandle writeData:pFrame.pBuffer];
}

- (void)msgAddObject:(NotifyMessageModel *)msg{
    [self.notifyMessages addObject:msg];
    if (self.delegate && [self.delegate respondsToSelector:@selector(onMessageChanged:)]) {
        [self.delegate onMessageChanged:self.notifyMessages];
    }
}

-(NSString *)getTime:(NSTimeInterval)time {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:time]];
    return dateTime;
}
@end
