//
//  WebSocketClient.m
//  LoginDemo
//
//  Created by 初程程 on 2018/7/4.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "WebSocketClient.h"
#import <IMSApiClient/IMSApiClient.h>
#import <AlinkAppExpress/LKAppExpress.h>
#import <IMSAccount/IMSAccountService.h>
#import <IMSAuthentication/IMSAuthentication.h>
#import "RNSendToJsReact.h"
@interface WebSocketClient()<LKAppExpConnectListener,LKAppExpDownListener>
@property (nonatomic ,assign)BOOL isConnect;
@end
@implementation WebSocketClient
+ (WebSocketClient *)sharedInstance{
  static WebSocketClient *socket;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    socket = [[WebSocketClient alloc] init];
  });
  return socket;
}

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

- (void)initConfig{
//  IMSConfiguration * imsconfig = [IMSConfiguration sharedInstance];
//  LKAEConnectConfig * config = [LKAEConnectConfig new];
//  config.appKey = imsconfig.appKey;
//  config.authCode = imsconfig.authCode;
//  // 指定长连接服务器地址。 （默认不填，SDK会使用默认的地址及端口。默认为国内华东节点。不要带 "协议://"，如果置为空，底层通道会使用默认的地址）
//  config.server = @"";
//  // 开启动态选择Host功能。 (默认 NO，海外环境请设置为 YES。此功能前提为 config.server 不特殊指定。）
//  config.autoSelectChannelHost = NO;
//  [[LKAppExpress sharedInstance]startConnect:config connectListener:self];
}
- (void)onConnectState:(LKAppExpConnectState) state{
  NSLog(@"AliLiving LKAppExpConnectState %ld", (long)state);
  self.isConnect = state==LKAppExpConnectStateConnected;
  
  NSString *tip = @"";
  
  if (self.isConnect) {
    
    tip = @"1";
    
  }else{
    
    tip = @"0";
  }
  
  [RNSendToJsReact emitEventWithName:@"AppExpConnectStateChange" andPayload:@{@"value":tip}];
  
}

- (void)startListener {
  IMSCredential *credential = [[IMSCredentialManager sharedManager] credential];
  
  if (credential.iotToken) {
    [[LKAppExpress sharedInstance] invokeWithTopic : @"/account/bind"  opts:nil        params:@{@"iotToken":credential.iotToken}
                                        respHandler:^(LKAppExpResponse * _Nonnull response) {
                                          if([response successed]){
                                            self.listenerBlock(nil);
                                          }else{
                                            self.listenerBlock(response.responseError);
                                          }
                                        }];
  }
}
- (void)stopListener:(void(^)(BOOL isSuccess))callback {
    [[LKAppExpress sharedInstance] invokeWithTopic:@"/account/unbind" opts:nil params:@{} respHandler:^(LKAppExpResponse * _Nonnull response) {
      if ([response successed]) {
        callback(YES);
      }else{
        callback(NO);
        //      [AlertShow showAlertWithMessage:@"长连接通道解绑失败"];
      }
    }];
}
- (void)invokeWithTopic:(NSString *)topic
                 params:(id)params {
  [[LKAppExpress sharedInstance] invokeWithTopic:topic opts:nil params:params respHandler:^(LKAppExpResponse * _Nonnull response) {
    
  }];
}

- (void)publish:(NSString *)topic
         params:(id)params
 publishResolve:(RCTPromiseResolveBlock)resolve
publishRejecter:(RCTPromiseRejectBlock)rejecter {
    [[LKAppExpress sharedInstance] publish:topic params:params complete:^(NSError * _Nonnull error) {
        if (error) {
            NSLog(@"AliLiving publish onFailure");
            rejecter(@"publishRejecter", @"publish onFailure", nil);
        } else {
            NSLog(@"AliLiving publish onSuccess");
            resolve(@{});
        }
    }];
}

- (void)subscribeTopic:(NSString *)topic {
  [[LKAppExpress sharedInstance] subscribe:topic complete:^(NSError * _Nullable error) {
    if (error) {
      NSLog(@"AliLiving subscribe onFailed, topic=%@", topic);
      self.subscribeListenerBlock(error);
    } else {
      NSLog(@"AliLiving subscribe onSuccess, topic=%@", topic);
      if ([self.topics indexOfObject:topic] >= 0) {
        return;
      } else {
        if (self.topics.count == 0) {
          [[LKAppExpress sharedInstance] removeDownStreamListener:self];
          [[LKAppExpress sharedInstance] addDownStreamListener:NO listener:self];
        }

        [self.topics addObject:topic];
    }

      self.subscribeListenerBlock(nil);
    }
  }];
}

- (void)cancelTopic:(NSString *)topic {
  [[LKAppExpress sharedInstance] unsubscribe:topic complete:^(NSError * _Nullable error) {
    if (error) {
      NSLog(@"AliLiving unsubscribe onFailed, topic=%@", topic);
    }else{
      NSLog(@"AliLiving unsubscribe onSuccess, topic=%@", topic);
      if ([self.topics indexOfObject:topic] >= 0) {
        [self.topics removeObject:topic];
      } else {
        return;
      }

      if (self.topics.count == 0) {
        [[LKAppExpress sharedInstance] removeDownStreamListener:self];
      }
    }
  }];
}

- (void)onDownstream:(NSString * _Nonnull)topic data:(id  _Nullable)data {
  //  [AlertShow showAlertWithMessage:[NSString stringWithFormat:@"%@%@",topic,data]];
  NSLog(@"AliLiving downstream onCommand topic=%@, data=%@", topic, data);
  NSString *replyData = nil;
  if ([data isKindOfClass:[NSString class]]) {
    replyData = data;
  } else if ([data isKindOfClass:[NSDictionary class]]) {
    replyData = [self toJSONString:data];
  }
  if (self.downstreamListenerBlock && replyData) {
    self.downstreamListenerBlock(topic, replyData);
  }
}

- (NSString *)toJSONString:(NSDictionary *)dict {
  NSData *data = [NSJSONSerialization dataWithJSONObject:dict
                                                 options:NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
                                                   error:nil];
  
  if (data == nil) {
    return nil;
  }
  
  NSString *string = [[NSString alloc] initWithData:data
                                           encoding:NSUTF8StringEncoding];
  return string;
}

- (BOOL)shouldHandle:(NSString * _Nonnull)topic {
  NSLog(@"AliLiving downstream shouldHandle topic=%@", topic);
  return [self.topics indexOfObject:topic] >= 0;
}

- (BOOL)connectState{
  return self.isConnect;
}
@end
