// This file is root file responsible for responding to events from JS and sending events to JS

#import "DyteHelper.h"
#import <React/RCTConvert.h>
#import "DyteSelfParticipant+Private.h"
#import "DyteParticipants+Private.h"
#import <React/RCTEventEmitter.h>
#import "DyteMeetingInfo+Private.h"
#import "DyteDelegateHandler.h"
#if __has_include("DyteMeetingView+Private.h")
#import "DyteMeetingView+Private.h"
#endif
//Reasoning behind certain things
//Note: this isn't written by an experienced iOS developer
//Why are we sending
@implementation DyteHelper {
    NSString *_currentEvent;
    DyteMeetingInfo *_meetingInfo;
    DyteSelfParticipant *_selfInfo;
    DyteParticipants *_participants;
}

- (instancetype)init
{

    if (self = [super init]) {
        _selfInfo = [DyteSelfParticipant sharedInstance];
        _participants = [DyteParticipants sharedInstance];
        _meetingInfo = [DyteMeetingInfo sharedInstance];
        _currentEvent = nil; //We don't do anything with _current Event
        [self initMessageEmit];
        [self startObservingDeviceOrientation];
    }
    return self;
}


- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (BOOL)requiresMainQueueSetup {
    return NO;
}

- (void)initMessageEmit {
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(receiveNotification:)
            name:@"DyteHelperToJSNotification"
            object:nil];
}


- (void) receiveNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"DyteHelperToJSNotification"]) {
        NSString* type = notification.userInfo[@"type"];
        if ([notification.userInfo objectForKey:@"data"]) {
            NSDictionary* data = notification.userInfo[@"data"];
            [self sendEventWithName:type body:data];
        } else {
            [self sendEventWithName:type body:NULL];
        }
    }
}

RCT_EXPORT_MODULE(DyteHelper)

RCT_EXPORT_METHOD(GetDeviceOrientation) {
  
}
// Self Participant Method
// -------
RCT_EXPORT_METHOD(SDKSelfVideo:(BOOL)enabled) {
    [_selfInfo setSelfVideo:enabled];
}
//

RCT_EXPORT_METHOD(SDKSelfBasic:
                  (NSString*)id
                  name:(NSString*)name
                  picture:(NSString*)picture
){
    [_selfInfo setUserInfo:id name:name picture:picture];
}

RCT_EXPORT_METHOD(SDKSelfAudio:(BOOL)enabled) {
    [_selfInfo setSelfAudioEnabled:enabled];
}

RCT_EXPORT_METHOD(SDKSelfPin:(BOOL)isPinned) {
    [_selfInfo setSelfPin:isPinned];
}

RCT_EXPORT_METHOD(SDKSelfScreenshare:(BOOL)isScreensharing) {
 //TODO: Implement Screen share
}
// --- End of Self Participant


// DyteMeetingInfo
// ------
RCT_EXPORT_METHOD(SDKMeetingConnect) {
 [_meetingInfo setMeetingConnected:true];
    [[DyteDelegateHandler new] call:NULL andSelector:@selector(meetingConnected)];
}

RCT_EXPORT_METHOD(SDKMeetingDisconnect) {
 [_meetingInfo setMeetingConnected:false];
    [[DyteDelegateHandler new] call:NULL andSelector:@selector(meetingDisconnect)];
    
}

RCT_EXPORT_METHOD(SDKMeetingJoined) {
  [_meetingInfo setMeetingJoined:true];
    [[DyteDelegateHandler new] call:NULL andSelector:@selector(meetingJoined)];
}

RCT_EXPORT_METHOD(SDKMeetingEnded) {

    [_selfInfo setAllValueNil];
    [_participants setAllValueNil];
    [_meetingInfo setAllValueNil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    #if __has_include("DyteMeetingView+Private.h")
    DyteMeetingView *view = [DyteMeetingView getView];
    if (view) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [view removeFromSuperview];
        });
    }
    #endif
    [[DyteDelegateHandler new] call:NULL andSelector:@selector(meetingEnded)];
  [_meetingInfo setMeetingJoined:false];
}

RCT_EXPORT_METHOD(stopService) {
    [[DyteDelegateHandler new] call:NULL andSelector:@selector(meetingEnded)];

}

RCT_EXPORT_METHOD(SDKActiveSpeaker:(NSString*)peerId) {
    [_meetingInfo setActiveSpeaker:peerId];
    [[DyteDelegateHandler new] call:peerId andSelector:@selector(activeSpeaker)];
}

// --- Dyte Participants
// -------
RCT_EXPORT_METHOD(SDKParticipantLeave:(NSString*)peerId) {
    [_participants onParticipantLeft:peerId];

}

RCT_EXPORT_METHOD(SDKParticipantJoin:
                  (NSString*)id
                  name:(NSString*)name
                  picture:(NSString*)picture
                  clientSpecificId:(NSString*)clientSpecificId
                  audioEnabled:(BOOL)audioEnabled
                  videoEnabled:(BOOL)videoEnabled
                  isPinned:(BOOL)isPinned
                  isScreensharing:(BOOL)isScreensharing
){
    [_participants createParticipant:id name:name picture:picture clientSpecificId:clientSpecificId audioEnabled:audioEnabled videoEnabled:videoEnabled isPinned:isPinned isScreensharing:isScreensharing];
}

RCT_EXPORT_METHOD(SDKParticipantUpdate:
                  (NSString*)id
                  audioEnabled:(BOOL)audioEnabled
                  videoEnabled:(BOOL)videoEnabled
                  isPinned:(BOOL)isPinned
                  isScreensharing:(BOOL)isScreensharing
){
    [_participants updateParticipant:id audioEnabled:audioEnabled videoEnabled:videoEnabled isPinned:isPinned isScreensharing:isScreensharing];
}

// -----
RCT_EXPORT_METHOD(SDKMessage:(NSObject*)message) {
    [_meetingInfo setMessage:message];
    [[DyteDelegateHandler new] call:message andSelector:@selector(message)];
}

RCT_EXPORT_METHOD(SDKRoomMessage:(NSObject*)roomMessage) {
    [_meetingInfo setRoomMessage:roomMessage];
    [[DyteDelegateHandler new] call:roomMessage andSelector:@selector(roomMessage)];
}


// Device Orientation
RCT_EXPORT_METHOD(isForcedLandscape:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
}

RCT_EXPORT_METHOD(forceLandscape) {

}

RCT_EXPORT_METHOD(resetOrientation) {

}




- (NSString*) getDeviceOrientation {
    NSLog(@"Device Orientation Changed");
    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft)
    {
      return @"landscapeLeft";
    }
   else if ([[UIDevice currentDevice] orientation ] == UIDeviceOrientationLandscapeRight) {
     return @"landscapeRight";
   }
   else if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
     return @"portrait";
    }
   else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
     return @"portraitDown";
   } else {
     return @"unknown";
   }
}

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(deviceOrientation) {
  return [self getDeviceOrientation];
}

- (void)startObservingDeviceOrientation {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationListener:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
    
- (void) orientationListener:(NSNotification *)notification {
    NSString *orientation = [self getDeviceOrientation];
     return [self sendEventWithName:@"DEVICE_ORIENTATION" body:@{@"orientation": orientation}];
}



- (NSArray<NSString *> *)supportedEvents {
    return @[@"SELF_TOGGLE_AUDIO", @"SELF_TOGGLE_VIDEO", @"SELF_PIN", @"SELF_UNPIN", @"SELF_TOGGLE_SCREENSHARING", @"UPDATE_UICONFIG", @"LEAVE_ROOM", @"DEVICE_ORIENTATION"];
}


@end
