//
//  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"

@interface OffcnIMSocketManager ()<OIMCoreDelegate>

@property (nonatomic, strong) OIMCoreAdapter *adapter;
@property (nonatomic, strong) NSMutableArray *msgArr;
@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;
    }
    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;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObjectOnSafe:@"39.102.42.185" forKey:@"server_ip"];
    [dic setObjectOnSafe:[NSNumber numberWithInteger:1280] 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:token forKey:@"token"];
    
    NSString *session_id = [SDGeneralTool getNowSSSTimeTimestamp];
    [dic setObjectOnSafe:session_id forKey:@"session_id"];
    [dic setObjectOnSafe:@"websocket" 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);
        }
    }
}

//Z_CONN_IM_SRV_OK,连接成功
//Z_CONN_IM_SRV_FAILED,连接失败
//Z_CONN_IM_SRV_BROKEN,连接断开
//Z_DISCONN_IM_SRV_OK,手动断开成功
-(void)OnOImCoreEventWithCode:(int)code context:(const char *)context{
    //连接状态
    if (code == 1 || code == 2) {
        [self.adapter DisConnectImServer];
    }
    
    if (self.connectStatus) {
        NSString *message = [NSString stringWithUTF8String:context];
        if (code == 0) {
            self.IMConnectStatus = OffcnIMConnectStatusSuccess;
            self.connectStatus(OffcnIMConnectStatusSuccess,message);
        }else if (code == 1){
            self.IMConnectStatus = OffcnIMConnectStatusFail;
            self.connectStatus(OffcnIMConnectStatusFail,message);
        }else if (code == 2){
            self.IMConnectStatus = OffcnIMConnectStatusBreak;
            self.connectStatus(OffcnIMConnectStatusBreak,message);
        }else if (code == 3){
            self.IMConnectStatus = OffcnIMConnectStatusDisConnectOK;
            self.connectStatus(OffcnIMConnectStatusDisConnectOK,message);
        }
    }
}
@end
