//
//  OffcnIMSocketManager.m
//  OffcnIMSDKiOS
//
//  Created by vockey on 2020/8/24.
//  Copyright © 2020 offcn. All rights reserved.
//

#import "OffcnIMSocketManager.h"
#import <oimcore/oimcoreAdapter.h>
#import "ZYJMJExtension.h"
#import "DataSafe.h"
#import "SDGeneralTool.h"
#import "OffcnIMZYJFMDBHandler.h"
#import "SDGeneralDefine.h"

@interface OffcnIMSocketManager ()<OIMCoreDelegate>

@property (nonatomic, strong) OIMCoreAdapter *adapter;
@property (nonatomic, strong) NSMutableArray *msgArr;

@property (nonatomic, assign) BOOL isActive;

@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
@end

@implementation OffcnIMSocketManager

-(NSMutableArray *)msgArr{
    if (!_msgArr) {
        _msgArr = [NSMutableArray array];
    }
    return _msgArr;
}

static OffcnIMSocketManager *socketManager;
+(OffcnIMSocketManager *)defaultService{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        socketManager = [[OffcnIMSocketManager alloc] init];
    });
    return socketManager;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        self.adapter = [OIMCoreAdapter sharedOIMCore];
        [self.adapter Initialize];
        self.adapter.delegate = self;
        
        self.isActive = YES;
        self.backgroundTask = UIBackgroundTaskInvalid;
        
        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
        
        [defaultCenter addObserver:self
                          selector:@selector(appWillResignActive)
                              name:UIApplicationWillResignActiveNotification
                            object:nil];
        
        [defaultCenter addObserver:self
                          selector:@selector(appDidEnterBackground)
                              name:UIApplicationDidEnterBackgroundNotification
                            object:nil];
        
        [defaultCenter addObserver:self
                          selector:@selector(appDidBecomeActive)
                              name:UIApplicationDidBecomeActiveNotification
                            object:nil];
        
        [defaultCenter addObserver:self
        selector:@selector(appWillTerminateNotification)
            name:UIApplicationWillTerminateNotification
          object:nil];
    }
    return self;
}

//建立连接
-(void)connectIMServerWithAccount_id:(NSString *)account_id token:(NSString *)token{
    
//    kcp和websocket地址信息：
//    server_ip : "39.102.42.185"
//    server_port_websocket : 1280
//    server_port_kcp:1281
//
//    websocket + tls地址信息：
//    server_ip : test-im.offcncloud.com
//    server_port : 1279
//    connection_type = ["kcp，1281", "websocket，1280"]
//    tls = ["disable", "enable"]
    
    self.msg_fromId = account_id;
    self.token = token;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObjectOnSafe:@"39.102.42.185" forKey:@"server_ip"];
    [dic setObjectOnSafe:[NSNumber numberWithInteger:1281] forKey:@"server_port"];
    [dic setObjectOnSafe:account_id forKey:@"account_id"];
    [dic setObjectOnSafe:@"offcn_live" forKey:@"app_id"];
    [dic setObjectOnSafe:@"ios" forKey:@"device_type"];
    [dic setObjectOnSafe:KUUIDString forKey:@"deviceid"];
    [dic setObjectOnSafe:token forKey:@"token"];
    
    NSString *session_id = [NSString stringWithFormat:@"%@%@",KUUIDString,[SDGeneralTool getNowSSSTimeTimestamp]];
    [dic setObjectOnSafe:session_id forKey:@"session_id"];
    [dic setObjectOnSafe:@"kcp" forKey:@"connection_type"];
    [dic setObjectOnSafe:@"disable" forKey:@"tls"];
    
    [self connectIMServerWithParam:[dic mj_ZYJJSONString]];
}
-(void)connectIMServerWithParam:(NSString *)param{
    [self.adapter ConnectImServerWithParam:param];
}

//断开连接
-(void)disConnectIMServer{
    [self.adapter DisConnectImServer];
}

//收到消息
-(void)OnOImCoreMessageWithMessage:(const char *_Nonnull)message msgLength:(int)len{
//    "{\"type\":1,\"body\":{\"session_id\":\"a05517f0-ddec-11ea-88a4-4a5555fb6ab4\",\"msg_id\":\"d5f9b600-e28f-11ea-88a4-4a5555fb6ab4\",\"version\":1,\"send_time\":\"2020-08-20 10:49:58\",\"msg_seq\":1597891798,\"msg_from\":\"jfdfjei0343\",\"msg_scope\":1,\"msg_type\":1,\"msg_content\":{\"msg\":\"随机数298\"}}}"
    
    NSString *revStr = [NSString stringWithUTF8String:message];
    OffcnIMModel *IMModel = [OffcnIMModel mj_ZYJobjectWithKeyValues:revStr];
    
    if ([self.msg_fromId isEqualToString:IMModel.body.msg_from]) {
        return;
    }
    
    NSString *msg_id = IMModel.body.msg_id;
    if (!msg_id) {
        return;
    }
    
    if (self.msgArr.count) {
        if ([self.msgArr containsObject:msg_id]) {
            //消息重复，丢弃
        }else{
            if (self.msgArr.count>=100) {
                [self.msgArr removeObjectAtIndex:0];
            }
            
            [self.msgArr addObject:msg_id];
            
            //存数据库
            OffcnIMBodyModel *body = IMModel.body;
            body.isSentSuccess = 1;
            body.bymyself = 0;
            body.isRead = 0;
            [[OffcnIMZYJFMDBHandler sharedInstance] insertChatInfoToFMDBWithModel:body];
            [[OffcnIMZYJFMDBHandler sharedInstance] chatlistCacheInfo:body callback:nil];
            
            if (self.connectReceiveMessage) {
                self.connectReceiveMessage(IMModel);
            }
        }
    }else{
        [self.msgArr addObject:msg_id];
        
        //存数据库
        OffcnIMBodyModel *body = IMModel.body;
        body.isSentSuccess = 1;
        body.bymyself = 0;
        body.isRead = 0;
        [[OffcnIMZYJFMDBHandler sharedInstance] insertChatInfoToFMDBWithModel:body];
        [[OffcnIMZYJFMDBHandler sharedInstance] chatlistCacheInfo:body callback:nil];
        
        if (self.connectReceiveMessage) {
            self.connectReceiveMessage(IMModel);
        }
    }
}

//typedef enum
//{
//    Z_CONN_IM_SRV_OK,
//    Z_CONN_IM_SRV_FAILED,
//
//    Z_CONN_IM_SRV_BROKEN,
//
//    Z_DISCONN_IM_SRV_OK,
//
//}OImEventCode;

//typedef NS_ENUM(NSUInteger, OffcnIMConnectStatus) {
//    OffcnIMConnectStatusSuccess = 0,        //连接成功
//    OffcnIMConnectStatusFail = 1,           //连接失败
//    OffcnIMConnectStatusBreak = 2,          //连接断开
//    OffcnIMConnectStatusDisConnectOK = 3,   //手动断开成功
//    OffcnIMConnectStatusOverLimit = 3001,        //连接数量超过限制
//    OffcnIMConnectStatusUserNoExist = 5002,        //用户不存在
//    OffcnIMConnectStatusTokenInvalid = 5003,        //token已失效
//    OffcnIMConnectStatusKickout = 8003,        //账号被踢
//};
-(void)OnOImCoreEventWithCode:(OImEventCode)code errorCode:(int)nErrorCode context:(const char *_Nonnull)context{
    //连接状态
    if (code == Z_CONN_IM_SRV_FAILED || code == Z_CONN_IM_SRV_BROKEN || nErrorCode == OffcnIMConnectStatusOverLimit || nErrorCode == OffcnIMConnectStatusUserNoExist || nErrorCode == OffcnIMConnectStatusTokenInvalid || nErrorCode == OffcnIMConnectStatusKickout) {
        [self.adapter DisConnectImServer];
    }
    
    if (self.connectStatus) {
        NSString *message = [NSString stringWithUTF8String:context];
        
        if (nErrorCode == OffcnIMConnectStatusOverLimit){
            self.IMConnectStatus = OffcnIMConnectStatusOverLimit;
            self.connectStatus(OffcnIMConnectStatusOverLimit,message);
        }else if (nErrorCode == OffcnIMConnectStatusUserNoExist){
            self.IMConnectStatus = OffcnIMConnectStatusUserNoExist;
            self.connectStatus(OffcnIMConnectStatusUserNoExist,message);
        }else if (nErrorCode == OffcnIMConnectStatusTokenInvalid){
            self.IMConnectStatus = OffcnIMConnectStatusTokenInvalid;
            self.connectStatus(OffcnIMConnectStatusTokenInvalid,message);
        }else if (nErrorCode == OffcnIMConnectStatusKickout){
            self.IMConnectStatus = OffcnIMConnectStatusKickout;
            self.connectStatus(OffcnIMConnectStatusKickout,message);
        }else if (code == Z_CONN_IM_SRV_OK) {
            self.IMConnectStatus = OffcnIMConnectStatusSuccess;
            self.connectStatus(OffcnIMConnectStatusSuccess,message);
        }else if (code == Z_CONN_IM_SRV_FAILED){
            self.IMConnectStatus = OffcnIMConnectStatusFail;
            self.connectStatus(OffcnIMConnectStatusFail,message);
        }else if (code == Z_CONN_IM_SRV_BROKEN){
            self.IMConnectStatus = OffcnIMConnectStatusBreak;
            self.connectStatus(OffcnIMConnectStatusBreak,message);
        }else if (code == Z_DISCONN_IM_SRV_OK){
            self.IMConnectStatus = OffcnIMConnectStatusDisConnectOK;
            self.connectStatus(OffcnIMConnectStatusDisConnectOK,message);
        }
    }
}

-(void)manualSendLocalNotificationWithModel:(OffcnIMModel *)model{
    if (self.isActive) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            UILocalNotification *backgroudMsg = [[UILocalNotification alloc] init];
            if (backgroudMsg) {
                backgroudMsg.timeZone = [NSTimeZone defaultTimeZone];
                backgroudMsg.alertBody = @"您有一条新的消息";
                backgroudMsg.applicationIconBadgeNumber = 1;
                backgroudMsg.alertAction = @"查看";
                NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
                backgroudMsg.userInfo = infoDic;
                [[UIApplication sharedApplication] presentLocalNotificationNow:backgroudMsg];
            }
        });
    }
}


- (void)appWillResignActive {
//    [self.sessionManager disconnectWithDisconnectHandler:nil];
}

- (void)appDidEnterBackground {
//    if (!self.sessionManager.requiresTearDown) {
//        // we don't want to tear down session as it's already closed
//        return;
//    }
    
    self.isActive = NO;
    
    __weak typeof(self) weakSelf = self;
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf endBackgroundTask];
    }];
}

- (void)appDidBecomeActive {
    self.isActive = YES;
    
    if (self.IMConnectStatus != OffcnIMConnectStatusSuccess && self.msg_fromId && self.token) {
        //建立连接
        [self connectIMServerWithAccount_id:self.msg_fromId token:self.token];
    }
}

- (void)appWillTerminateNotification {
    //断开连接
    [self disConnectIMServer];
}

- (void)endBackgroundTask {
    if (self.backgroundTask) {
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }
}
- (void)dealloc {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [defaultCenter removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [defaultCenter removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [defaultCenter removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
@end
