//
//  mqtt.m
//  mqtt
//
//  Created by 程石亮 on 2018/1/13.
//  Copyright © 2018年 Chengsl02. All rights reserved.
//

#import "mqtt.h"
#import "VKDes3Handle.h"
#import <MQTTClient.h>
#import <MQTTSessionManager.h>
#import <React/RCTUtils.h>
#import "RCTEventDispatcher.h"
@interface mqtt ()<MQTTSessionManagerDelegate,MQTTSessionDelegate>
@property (nonatomic, strong) MQTTSessionManager *sessionManager;
@property (nonatomic, strong) MQTTSession *session;

@end
static mqtt *shareInstance = nil;
@implementation mqtt
@synthesize bridge = _bridge;
RCT_EXPORT_MODULE();
- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
- (NSArray<NSString *> *)supportedEvents
{
    return @[@"connect"];//供js调用方法列表
}
- (NSDictionary *)constantsToExport{//提供给js的常量列表
    return @{};
}
RCT_EXPORT_METHOD(connect)
{
    [[mqtt share] connect];
}
+ (instancetype)share{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[[self class] alloc] init];
    });
    return shareInstance;
}

- (void)connect{
    shareInstance.session = [MQTTSession new];
    shareInstance.session.delegate = shareInstance;
    shareInstance.session.keepAliveInterval = 60;
    shareInstance.session.userName  = @"LTAICHZNM08qwsF1";
    shareInstance.session.clientId  = @"GID_HA-SIGN_IN@@@test01";
    shareInstance.session.password = [VKDes3Handle hmacsha1:@"GID_HA-SIGN_IN" key:@"GcGKhlT34MsMD1FkbVlP8EtXDbi7mL"];
    [shareInstance.session connectToHost:@"post-cn-45908degu01.mqtt.aliyuncs.com" port:1883 usingSSL:NO connectHandler:^(NSError *error) {
        NSLog(@"连接错误---%@",error);
    }];
}

- (void)newMessage:(MQTTSession *)session
              data:(NSData *)data
           onTopic:(NSString *)topic
               qos:(MQTTQosLevel)qos
          retained:(BOOL)retained
               mid:(unsigned int)mid{
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"MQTT RECEIVE DATA --- %@---topic:%@",dataString,topic);
    [self.bridge.eventDispatcher sendAppEventWithName:@"receiveMessage" body:@{@"message": dataString}];
}
- (void)handleEvent:(MQTTSession *)session
              event:(MQTTSessionEvent)eventCode
              error:(NSError *)error{
    switch (eventCode) {
        case MQTTSessionEventConnected:
        {
            NSLog(@"------连接成功");
            [shareInstance.session subscribeToTopic:@"HA-SIGN_IN/p2p/GID_HA-SIGN_IN@@@test01" atLevel:0 subscribeHandler:^(NSError *error, NSArray<NSNumber *> *gQoss){
                if (error) {
                    NSLog(@"Subscription failed %@", error.localizedDescription);
                } else {
                    NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
                }
            }];
        }
            break;
        case MQTTSessionEventConnectionRefused:
            NSLog(@"------连接被拒");
            break;
        case MQTTSessionEventConnectionClosed:
        {
            NSLog(@"------连接关闭");
            [shareInstance.session connectToHost:@"post-cn-45908degu01.mqtt.aliyuncs.com" port:1883 usingSSL:NO connectHandler:^(NSError *error) {
                NSLog(@"连接错误---%@",error);
            }];
        }
            break;
        case MQTTSessionEventConnectionError:
            NSLog(@"------连接出错");
            break;
        case MQTTSessionEventProtocolError:
            NSLog(@"------连接协议错误");
            break;
        case MQTTSessionEventConnectionClosedByBroker:
            NSLog(@"------连接中断");
            break;
        default:
            break;
    }
}
- (void)subAckReceived:(MQTTSession *)session
                 msgID:(UInt16)msgID
           grantedQoss:(NSArray<NSNumber *> *)qoss{
    
}
@end
