#import "RTCMeetingSDK.h"
#import "RNMeetView.h"

@implementation RCTMeetingSDK{
  RNMeetView *meetView;
}

NSString *api_service = @"https://webhook-core2.hoctructuyentrans.com";
NSString *server_url = @"https://meet.jit.si";

RCT_EXPORT_MODULE(OnmeetingSdk);
RCT_EXPORT_VIEW_PROPERTY(onConferenceJoined, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onConferenceTerminated, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onConferenceWillJoin, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onAudioMutedChanged, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onParticipantJoined, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onParticipantLeft, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onEndpointTextMessageReceived, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onScreenShareToggled, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onParticipantsInfoRetrieved, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onChatMessageReceived, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onChatToggled, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onVideoMutedChanged, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onReadyToClose, RCTBubblingEventBlock);
RCT_EXPORT_VIEW_PROPERTY(onEnteredPip, RCTBubblingEventBlock);



- (UIView *)view
{
  meetView = [[RNMeetView alloc] init];
  meetView.delegate = self;
  return meetView;
}

NSString *room = @"";

RCT_EXPORT_METHOD(openMeeting:
                  (NSString *)publicKey
                  accessToken:(NSString *)accessToken
                  resolve: (RCTPromiseResolveBlock) resolve
                  reject: (RCTPromiseRejectBlock) reject){
    
  @try {
    if(publicKey == NULL || accessToken == NULL){
      resolve(@"0");
      return;
    }
    
    [self getRoomInfo:publicKey :accessToken];
    
    if(room == @""){
      resolve(@"-1");
      return;
    }
    
    dispatch_sync(dispatch_get_main_queue(), ^{
      OnMeetingMeetConferenceOptions *options = [OnMeetingMeetConferenceOptions fromBuilder:^(OnMeetingMeetConferenceOptionsBuilder *builder) {
        builder.serverURL = [NSURL URLWithString:server_url];
        builder.audioOnly = NO;
        builder.audioMuted = NO;
        builder.videoMuted = NO;
 
        [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
        [builder setFeatureFlag:@"pip.enabled" withBoolean:YES];
        [builder setFeatureFlag:@"ios.screensharing.enabled" withBoolean:YES];
        [builder setFeatureFlag:@"meeting-name.enabled" withBoolean:NO];
		[builder setFeatureFlag:@"security-options.enabled" withBoolean:NO];
        [builder setFeatureFlag:@"speakerstats.enabled" withBoolean:NO];
        [builder setFeatureFlag:@"prejoinpage.enabled" withBoolean:NO];
    
        builder.room = room;
      }];
      [meetView join:options];
      resolve(@"1");
    });

  } @catch (NSException *error) {
    reject(@"MEETING_SDK", @"Failed to Join", error);
  }

}

- (NSArray<NSString *> *) supportedEvents {
  return @[];
}


#pragma mark RNMeetViewDelegate

- (void)conferenceJoined:(NSDictionary *)data {
    RCTLogInfo(@"Conference joined");
    if (!meetView.onConferenceJoined) {
        return;
    }

  meetView.onConferenceJoined(data);
}

- (void)conferenceTerminated:(NSDictionary *)data {
    RCTLogInfo(@"Conference terminated");
    if (!meetView.onConferenceTerminated) {
        return;
    }

  meetView.onConferenceTerminated(data);
}

- (void)conferenceWillJoin:(NSDictionary *)data {
    RCTLogInfo(@"Conference will join");
    if (!meetView.onConferenceWillJoin) {
        return;
    }

  meetView.onConferenceWillJoin(data);
}

- (void)onAudioMutedChanged:(NSDictionary *)data {
  RCTLogInfo(@"Audio muted changed");
    if (!meetView.onAudioMutedChanged) {
        return;
    }
  meetView.onAudioMutedChanged(data);
}

- (void)onParticipantJoined:(NSDictionary *)data{
  RCTLogInfo(@"Participant joined");
    if (!meetView.onParticipantJoined){
     return;
    }
  meetView.onParticipantJoined(data);
}

- (void)onParticipantLeft:(NSDictionary *)data{
  RCTLogInfo(@"Participant left");
   if (!meetView.onParticipantLeft){
     return;
   }
  meetView.onParticipantLeft(data);
}

- (void)onEndpointTextMessageReceived:(NSDictionary *)data{
  RCTLogInfo(@"Endpoint text message received");
   if (!meetView.onEndpointTextMessageReceived){
     return;
   }
  meetView.onEndpointTextMessageReceived(data);
}

- (void)onScreenShareToggled:(NSDictionary *)data{
  RCTLogInfo(@"Screen share toggled");
   if (!meetView.onScreenShareToggled){
     return;
   }
  meetView.onScreenShareToggled(data);
}

- (void)onParticipantsInfoRetrieved:(NSDictionary *)data{
  RCTLogInfo(@"Participants info retrieved");
   if (!meetView.onParticipantsInfoRetrieved){
     return;
   }
  meetView.onParticipantsInfoRetrieved(data);
}

- (void)onChatMessageReceived:(NSDictionary *)data{
  RCTLogInfo(@"Chat message received");
   if (!meetView.onChatMessageReceived){
     return;
   }
  meetView.onChatMessageReceived(data);
}

- (void)onChatToggled:(NSDictionary *)data{
  RCTLogInfo(@"Chat toggled");
   if (!meetView.onChatToggled){
     return;
   }
  meetView.onChatToggled(data);
}

- (void)onVideoMutedChanged:(NSDictionary *)data{
  RCTLogInfo(@"Video muted changed");
   if (!meetView.onVideoMutedChanged){
     return;
   }
  meetView.onVideoMutedChanged(data);
}

- (void)onReadyToClose:(NSDictionary *)data{
  RCTLogInfo(@"Meeting close");
   if (!meetView.onReadyToClose){
     return;
   }
  meetView.onReadyToClose(data);
}

- (void)enterPictureInPicture:(NSDictionary *)data {
  RCTLogInfo(@"Enter Picture in Picture");
  if (!meetView.onEnteredPip) {
      return;
  }
  meetView.onEnteredPip(data);
}

//=======
- (void)getRoomInfo:(NSString *)publicKey
                   :(NSString *)accessToken{
  dispatch_semaphore_t sema = dispatch_semaphore_create(0);


  
  NSString *apiUrl = [NSString stringWithFormat:@"%@/room/openRoom", api_service];
  NSString *params = [NSString stringWithFormat:@"{\"publicKey\":\"%@\",\"accessToken\":\"%@\"}",publicKey, accessToken];
  NSData *postData = [[NSData alloc] initWithData:[params dataUsingEncoding:NSUTF8StringEncoding]];
  
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setURL:[NSURL URLWithString:apiUrl]];
  [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  [request setHTTPBody:postData];
  [request setHTTPMethod:@"POST"];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
  completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
      NSLog(@"%@", error);
      dispatch_semaphore_signal(sema);
    } else {
      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
      NSError *parseError = nil;
      NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
      NSLog(@"response %@",responseDictionary);
      if(responseDictionary[@"data"][@"error"] == NO){
        room = [NSString stringWithFormat:@"https://meet.vigohd.net/%@?jwt=%@",responseDictionary[@"data"][@"meetingId"], responseDictionary[@"data"][@"accessToken"]];
      }
      
      dispatch_semaphore_signal(sema);
    }

  }];
  [dataTask resume];
  dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

@end
