#import "DyteRNBluetoothHeadsetDetect.h"
#import <AVFoundation/AVFoundation.h>
#import <React/RCTLog.h>

@implementation DyteRNBluetoothHeadsetDetect

RCT_EXPORT_MODULE()

// Called when this module's first listener is added.
-(void)startObserving {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioHardwareRouteChanged:) name:AVAudioSessionRouteChangeNotification object:nil];
    [self updateConnectedDevice];
}

// Called when this module's last listener is removed, or on dealloc.
-(void)stopObserving {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

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

- (void)updateConnectedDevice {
    NSMutableArray *devices = [NSMutableArray array];
    
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortBluetoothHFP] ||
            [[desc portType] isEqualToString:AVAudioSessionPortBluetoothA2DP] ||
            [[desc portType] isEqualToString:AVAudioSessionPortBluetoothLE]) {
            [devices addObject:[desc portName]];
        }
    }
    [self sendEventWithName:@"onAudioDeviceChanged" body:@{@"devices": devices}];
}

- (void)audioHardwareRouteChanged:(NSNotification *)notification {
    // NSNumber *reason = [notification.userInfo objectForKey:AVAudioSessionRouteChangeReasonKey];
    // if ([reason unsignedIntegerValue] == AVAudioSessionRouteChangeReasonNewDeviceAvailable ||
    //     [reason unsignedIntegerValue] == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
    // }
    [self updateConnectedDevice];
}

RCT_EXPORT_METHOD(isBluetoothHeadsetConnected:(RCTPromiseResolveBlock)resolve
                                      reject:(RCTPromiseRejectBlock)reject)
{
    BOOL bluetoothHeadsetPluggedIn = [self isBluetoothDeviceConnected];
    resolve(@{
        @"isBluetoothHeadsetPluggedIn": bluetoothHeadsetPluggedIn ? @YES : @NO,
    });
}

- (BOOL)isBluetoothDeviceConnected {
    NSMutableArray *devices = [NSMutableArray array];
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortBluetoothHFP] ||
            [[desc portType] isEqualToString:AVAudioSessionPortBluetoothA2DP] ||
            [[desc portType] isEqualToString:AVAudioSessionPortBluetoothLE]) {
            [devices addObject:[desc portName]];
        }
    }
    if (!devices || !devices.count){
        return false;
    } else {
        return true;
    }
}

@end
