#import "CallCenter.h"
#import <React/RCTLog.h>
#import <BWFCallCenterFramework/BWFCallCenterFramework.h>

@implementation CallCenter

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(initSDK:(NSString *) apiKey errorCallback: (RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  BOOL isConfigured = [BWFCallCenter configureWithApiKey:apiKey];NSLog(@"apikey %@", apiKey);

  if (isConfigured) {
    [BWFCallCenter setCallCenterDelegate:self];
    [BWFCallCenter setCallCenterForRequesterDelegate:self];
    [BWFCallCenter startAsAnonymousRequester];

    successCallback(@[@"success"]);
  }
  else
  {
    errorCallback(@[@"Please enter correct api key"]);
  }
}

RCT_EXPORT_METHOD(stopSDK:(RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  [BWFCallCenter stop];
  successCallback(@[@"success"]);
}

RCT_EXPORT_METHOD(requestVoiceCallWithDisplayName:(NSString * _Nullable)name toGroup:(NSString * _Nonnull)groupName errorCallback: (RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  [BWFCallCenter requestVoiceCallWithDisplayName:name toGroup:groupName];
  successCallback(@[@"success"]);
}

RCT_EXPORT_METHOD(requestChatWithDisplayName:(NSString * _Nullable)name toGroup:(NSString * _Nonnull)groupName errorCallback: (RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  [BWFCallCenter requestChatWithDisplayName:name toGroup:groupName];
  successCallback(@[@"success"]);
}

RCT_EXPORT_METHOD(sendText:(NSString *)text toIdentifier:(NSString *)identifier errorCallback: (RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  [BWFCallCenter sendText:text toIdentifier:identifier resultBlock:^(NSString * _Nullable messageId) {
    successCallback(@[messageId]);
  }];
}

RCT_EXPORT_METHOD(sendImage:(NSString *)url toIdentifier:(NSString *)identifier errorCallback: (RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  [BWFCallCenter sendImage:url toIdentifier:identifier resultBlock:^(NSString * _Nullable messageId) {
    successCallback(@[messageId]);
  }];
}

RCT_EXPORT_METHOD(sendSeen:(NSString *)messageId toIdentifier:(NSString *)identifier errorCallback: (RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  [BWFCallCenter sendSeenStatusForMessageId:messageId toIdentifier:identifier];
  successCallback(@[@"success"]);
}

RCT_EXPORT_METHOD(endSupporting:(RCTResponseSenderBlock)errorCallback successCallback: (RCTResponseSenderBlock)successCallback) {
  BOOL isInAnyCallNow = [BWFCallCenter isInAnyCallNow];
  [BWFCallCenter endSupporting];
  
  if (!isInAnyCallNow) {
    [self sendEventWithName:@"registerEndSupporting" body:@{@"eventProperty": @{@"duration": @"0"}}];
  }
}


// @implementation BWFCallCenterProtocol
- (void) bwfCallCenterDidStartAsRequesterWithIdentifier:(NSString * _Nullable) identifier {
  NSLog(@"bwfCallCenterDidStartAsRequesterWithIdentifier - identifier = %@", identifier);
  [self sendEventWithName:@"registerStateSDK" body:@{@"eventProperty": @{ @"success": @true }}];
}

- (void) bwfCallCenterDidStop {
  NSLog(@"bwfCallCenterDidStop");
  [self sendEventWithName:@"registerStateSDK" body:@{@"eventProperty": @{ @"success": @false }}];
}

- (void) bwfCallCenterFailedWithError:(BWFCallCenterError * _Nonnull)error {
  NSLog(@"bwfMessageFailedWithError - error = %ld", (error.code));
  
  if (error.code == BWF_ERROR_CODE_CALLCENTER_NO_AVAILABLE_SUPPORTER) {
    // to do
  }
  
  if (error.code != BWF_ERROR_CODE_CALLCENTER_IS_DISCONNECTED_TO_SERVER) {
    // to do
  }
  
  NSString *errCode = [NSString stringWithFormat: @"%ld", (long)error.code];
  
  [self sendEventWithName:@"registerFailedError" body:@{@"eventProperty": @{@"code": errCode, @"description": error.description}}];
}

- (void) bwfCallCenterReceiveTextMessage:(NSString *)text conversationId:(NSString *)convId messageId:(NSString *)messageId from:(NSString *)identifier date:(NSDate *)date {
  NSLog(@"bwfCallCenterReceiveTextMessage - text=%@ - conversationId=%@ - msgId=%@ - from=%@ - date=%@", text, convId, messageId, identifier, date);
  
  NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
  
  // text, conversationId, messageId, identifier, date
  [self sendEventWithName:@"registerChatObserver"
                     body:@{@"eventProperty":
                            @{
                              @"text": text,
                              @"conversationId": convId,
                              @"messageId": messageId,
                              @"identifier": identifier,
                              @"date": @(timestamp)
                            }
                          }
   ];
}

- (void) bwfCallCenterReceiveImageMessage:(NSString *)url conversationId:(NSString *)convId messageId:(NSString *)messageId from:(NSString *)identifier date:(NSDate *)date {
  NSLog(@"bwfCallCenterReceiveImageMessage - text=%@ - conversationId=%@ - msgId=%@ - from=%@ - date=%@", url, convId, messageId, identifier, date);
  
  NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
  
  // url, conversationId, messageId, identifier, date
  [self sendEventWithName:@"registerChatObserver"
                     body:@{@"eventProperty":
                            @{
                                @"url": url,
                                @"conversationId": convId,
                                @"messageId": messageId,
                                @"identifier": identifier,
                                @"date": @(timestamp)
                              }
                            }
   ];
}

- (void) bwfCallCenterReceiveStatus:(EnumBWFCallCenterMessageStatus)status forMessageId:(NSString *)msgId from:(NSString *)identifier {
  NSLog(@"bwfCallCenterReceiveStatus - text=%d - msgId=%@ - from=%@", status, msgId, identifier);
  
  NSString *msgStatus;
  
  if (status == BWFCallCenterMessageStatusDelivered) {
    msgStatus = @"delivered";
  }
  else if (status == BWFCallCenterMessageStatusSeen) {
    msgStatus = @"seen";
  }
  else {
    msgStatus = @"failed";
  }
  
  // status, messageId, identifier
  [self sendEventWithName:@"registerChatObserver"
                     body:@{@"eventProperty":
                            @{
                                @"status": msgStatus,
                                @"messageId": msgId,
                                @"identifier": identifier
                              }
                            }
   ];
}

- (void) bwfCallCenterFinishCallPreparationTo:(NSString * _Nonnull)identifier isVideoCall:(BOOL)isVideoCall {
  NSLog(@"bwfCallCenterFinishCallPreparation - identifier = %@", identifier);
}

- (void)bwfCallCenterCallDidChangeToStateOutgoingTo:(NSString * _Nullable)identifier isVideoCall:(BOOL)isVideoCall {
  NSLog(@"bwfCallCenterCallDidChangeToStateOutgoing to: %@ - isVideoCall: %d", identifier, isVideoCall);
}

- (void)bwfCallCenterCallDidChangeToStateConnectedWith:(NSString * _Nullable)identifier isVideoCall:(BOOL)isVideoCall {
  NSLog(@"bwfCallCenterCallDidChangeToStateConnected with: %@ - isVideoCall: %d", identifier, isVideoCall);
}

- (void) bwfCallCenterCallDidChangeToStateEnd:(NSTimeInterval)totalDuration {
  NSLog(@"bwfCallCenterCallDidChangeToStateEnd - duration = %f", totalDuration);
  
  NSString *duration = [NSString stringWithFormat:@"%f", totalDuration];
  
  [self sendEventWithName:@"registerEndSupporting" body:@{@"eventProperty": @{@"duration": duration}}];
}

// @implementation BWFCallCenterForRequesterProtocol
- (void) bwfCallCenterDidFindSupporterViaRequest:(BWFRequestEntity * _Nonnull)request {
  NSLog(@"bwfCallCenterDidFindSupporterViaRequest - %@", (request.description));
  
  if (request.type == BWFCallCenterRequestTypeChat) {
    // Start chatting
    // request.toIdentifier
  }
  
  [self sendEventWithName:@"registerSupporterVia" body:@{@"eventProperty": @{@"identifier": request.toIdentifier}}];
}

- (void) bwfCallCenterDidTimeoutFindingSupporters:(BWFRequestEntity * _Nonnull)request {
  NSLog(@"bwfCallCenterDidTimeoutFindingSupporters");
}

- (void) bwfCallCenterShouldRateForLastSupport:(RatingCompletionHandler)completionHandler {
  NSLog(@"bwfCallCenterShouldRateForLastSupport");
}

// supported events
- (NSArray<NSString *> *)supportedEvents
{
  return @[@"registerSupporterVia", @"registerChatObserver", @"registerStateSDK", @"registerFailedError", @"registerEndSupporting"];
}



@end
