// CoreBluetooth bridge of the Unity plugin for iOS and macOS. Unity compiles it into the iOS player;
// Unity/macos/build-aidlab-ble-macos.sh builds it into Plugins/aidlab_ble_macos.dylib.
#import <CoreBluetooth/CoreBluetooth.h>
#import <Foundation/Foundation.h>

// One manager per connection: it scans, connects to the first peripheral its discovery callback accepts, and reports
// to the callbacks it was created with, each called with the manager's context on the manager's own queue.
extern "C" {

typedef void (*aidlab_ble_data_cb)(void* context, const uint8_t* data, int size);
// Events, read by AppleBLEConnector.cs:
// 1 connected (command characteristic notifying), 2 disconnected or failed to connect, 3 firmware revision,
// 4 hardware revision, 5 error, 6 current time written, 7 current time confirmed, 8 current time failed.
typedef void (*aidlab_ble_event_cb)(void* context, int evt, const char* message);
// A discovered peripheral with its identifier and advertised name; true connects to it and ends the scan.
typedef bool (*aidlab_ble_discovery_cb)(void* context, const char* identifier, const char* name);

void* aidlab_ble_create(void* context, aidlab_ble_data_cb data_cb, aidlab_ble_event_cb event_cb,
                        aidlab_ble_discovery_cb discovery_cb);
void aidlab_ble_destroy(void* manager);
bool aidlab_ble_write(void* manager, const uint8_t* data, int size);
int aidlab_ble_get_max_write_length(void* manager);

}  // extern "C"

namespace {
static CBUUID* kAidlabServiceUuid() {
    return [CBUUID UUIDWithString:@"44366e80-cf3a-11e1-9ab4-0002a5d5c51b"];
}
// Aidlab 1 and Aidmed One advertise only Heart Rate, so the scan looks for either service.
static CBUUID* kHeartRateServiceUuid() {
    return [CBUUID UUIDWithString:@"180D"];
}
static CBUUID* kAidlabCmdCharUuid() {
    return [CBUUID UUIDWithString:@"51366e80-cf3a-11e1-9ab4-0002a5d5c51b"];
}
static CBUUID* kDeviceInfoServiceUuid() {
    return [CBUUID UUIDWithString:@"180A"];
}
static CBUUID* kCurrentTimeServiceUuid() {
    return [CBUUID UUIDWithString:@"1805"];
}
static CBUUID* kCurrentTimeCharUuid() {
    return [CBUUID UUIDWithString:@"2A2B"];
}
static CBUUID* kFirmwareCharUuid() {
    return [CBUUID UUIDWithString:@"2A26"];
}
static CBUUID* kHardwareCharUuid() {
    return [CBUUID UUIDWithString:@"2A27"];
}
}  // namespace

@interface AidlabBleManager : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate>
@property(nonatomic, strong) CBCentralManager* central;
@property(nonatomic, strong) CBPeripheral* peripheral;
@property(nonatomic, strong) CBCharacteristic* cmdCharacteristic;
@property(nonatomic, strong) CBCharacteristic* firmwareCharacteristic;
@property(nonatomic, strong) CBCharacteristic* hardwareCharacteristic;
@property(nonatomic, strong) CBCharacteristic* currentTimeCharacteristic;
@property(nonatomic, strong) dispatch_queue_t queue;
@property(nonatomic) void* context;
@property(nonatomic) aidlab_ble_data_cb dataCb;
@property(nonatomic) aidlab_ble_event_cb eventCb;
@property(nonatomic) aidlab_ble_discovery_cb discoveryCb;
@property(nonatomic, strong) NSMutableArray<NSData*>* commandWriteQueue;
@property(nonatomic) BOOL commandWriteInFlight;
@property(nonatomic) BOOL commandWriteWithoutResponse;
@end

@implementation AidlabBleManager

// Firmware 4.0.0 or newer takes commands without response, older firmware with response. As in the Apple SDK, a
// characteristic without the required property fails the write instead of falling back to the other type: the
// firmware protocol, not the characteristic, decides how commands are acknowledged.
- (CBCharacteristicWriteType)cmdWriteType {
    return self.commandWriteWithoutResponse ? CBCharacteristicWriteWithoutResponse : CBCharacteristicWriteWithResponse;
}

- (void)emitEvent:(int)evt message:(NSString*)message {
    if(!self.eventCb) {
        return;
    }
    const char* cstr = message ? [message UTF8String] : "";
    self.eventCb(self.context, evt, cstr);
}

- (void)writeCurrentTime {
    if(!self.peripheral || !self.currentTimeCharacteristic) {
        return;
    }
    uint32_t ts = (uint32_t)[[NSDate date] timeIntervalSince1970];
    uint8_t bytes[4];
    bytes[0] = (uint8_t)(ts & 0xFF);
    bytes[1] = (uint8_t)((ts >> 8) & 0xFF);
    bytes[2] = (uint8_t)((ts >> 16) & 0xFF);
    bytes[3] = (uint8_t)((ts >> 24) & 0xFF);
    NSData* payload = [NSData dataWithBytes:bytes length:4];
    [self.peripheral writeValue:payload forCharacteristic:self.currentTimeCharacteristic type:CBCharacteristicWriteWithResponse];
    [self emitEvent:6 message:@"Current time written"];
}

- (instancetype)initWithContext:(void*)context
                         dataCb:(aidlab_ble_data_cb)dataCb
                        eventCb:(aidlab_ble_event_cb)eventCb
                    discoveryCb:(aidlab_ble_discovery_cb)discoveryCb {
    self = [super init];
    if(self) {
        self.context = context;
        self.dataCb = dataCb;
        self.eventCb = eventCb;
        self.discoveryCb = discoveryCb;
        self.commandWriteQueue = [NSMutableArray array];
        self.commandWriteInFlight = NO;
        self.commandWriteWithoutResponse = NO;
        self.queue = dispatch_queue_create("com.aidlab.unity.ble", DISPATCH_QUEUE_SERIAL);
        // Scanning starts once the central reports that Bluetooth is on.
        self.central = [[CBCentralManager alloc] initWithDelegate:self queue:self.queue];
    }
    return self;
}

- (void)scan {
    [self.central scanForPeripheralsWithServices:@[kAidlabServiceUuid(), kHeartRateServiceUuid()]
                                         options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO}];
}

- (void)stop {
    if(self.central) {
        [self.central stopScan];
    }
    if(self.peripheral) {
        [self.central cancelPeripheralConnection:self.peripheral];
    }
    self.peripheral = nil;
    self.cmdCharacteristic = nil;
    self.firmwareCharacteristic = nil;
    self.hardwareCharacteristic = nil;
    self.currentTimeCharacteristic = nil;
    [self.commandWriteQueue removeAllObjects];
    self.commandWriteInFlight = NO;
}

- (BOOL)writeBytes:(const uint8_t*)data size:(int)size {
    if(!self.peripheral || !self.cmdCharacteristic || !data || size <= 0) {
        return NO;
    }
    const CBCharacteristicProperties requiredProperty = self.commandWriteWithoutResponse
                                                            ? CBCharacteristicPropertyWriteWithoutResponse
                                                            : CBCharacteristicPropertyWrite;
    if(!(self.cmdCharacteristic.properties & requiredProperty)) {
        NSString* mode = self.commandWriteWithoutResponse ? @"without response" : @"with response";
        [self emitEvent:5 message:[NSString stringWithFormat:@"Command characteristic does not support writes %@", mode]];
        return NO;
    }
    NSData* payload = [NSData dataWithBytes:data length:(NSUInteger)size];
    [self.commandWriteQueue addObject:payload];
    [self drainCommandWrites];
    return YES;
}

- (void)drainCommandWrites {
    if(!self.peripheral || !self.cmdCharacteristic || self.commandWriteQueue.count == 0) {
        return;
    }

    CBCharacteristicWriteType writeType = [self cmdWriteType];
    if(writeType == CBCharacteristicWriteWithResponse) {
        if(self.commandWriteInFlight) {
            return;
        }
        NSData* payload = self.commandWriteQueue.firstObject;
        [self.commandWriteQueue removeObjectAtIndex:0];
        self.commandWriteInFlight = YES;
        [self.peripheral writeValue:payload forCharacteristic:self.cmdCharacteristic type:writeType];
        return;
    }

    while(self.commandWriteQueue.count > 0 && self.peripheral.canSendWriteWithoutResponse) {
        NSData* payload = self.commandWriteQueue.firstObject;
        [self.commandWriteQueue removeObjectAtIndex:0];
        [self.peripheral writeValue:payload forCharacteristic:self.cmdCharacteristic type:writeType];
    }
}

- (int)maxWriteLen {
    if(!self.peripheral) {
        return 20;
    }
    return (int)[self.peripheral maximumWriteValueLengthForType:[self cmdWriteType]];
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager*)central {
    (void)central;
    if(self.central.state == CBManagerStatePoweredOn) {
        if(!self.peripheral) {
            [self scan];
        }
    } else {
        [self emitEvent:5 message:@"Bluetooth not powered on"];
        // CoreBluetooth drops the peripheral without didDisconnectPeripheral, so the SDK replaces this manager, which
        // releases the device.
        if(self.peripheral) {
            [self emitEvent:2 message:@"Bluetooth not powered on"];
        }
    }
}

- (void)centralManager:(CBCentralManager*)central
    didDiscoverPeripheral:(CBPeripheral*)peripheral
        advertisementData:(NSDictionary<NSString*, id>*)advertisementData
                     RSSI:(NSNumber*)RSSI {
    (void)central;
    (void)RSSI;

    NSString* name = peripheral.name;
    NSString* advName = advertisementData[CBAdvertisementDataLocalNameKey];
    if(advName.length > 0) {
        name = advName;
    }

    // A discovery queued behind the accepted one must not take a second device.
    if(self.peripheral || name.length == 0 || !self.discoveryCb) {
        return;
    }

    if(!self.discoveryCb(self.context, peripheral.identifier.UUIDString.UTF8String, name.UTF8String)) {
        return;
    }

    [self.central stopScan];
    self.peripheral = peripheral;
    self.peripheral.delegate = self;
    [self.central connectPeripheral:peripheral options:nil];
}

- (void)centralManager:(CBCentralManager*)central didConnectPeripheral:(CBPeripheral*)peripheral {
    (void)central;
    if(peripheral != self.peripheral) {
        return;
    }
    [peripheral discoverServices:@[kAidlabServiceUuid(), kDeviceInfoServiceUuid(), kCurrentTimeServiceUuid()]];
}

- (void)centralManager:(CBCentralManager*)central didFailToConnectPeripheral:(CBPeripheral*)peripheral error:(NSError*)error {
    (void)central;
    if(peripheral == self.peripheral) {
        [self emitEvent:5 message:[NSString stringWithFormat:@"Failed to connect: %@", error]];
        [self emitEvent:2 message:@"Failed to connect"];
    }
}

- (void)centralManager:(CBCentralManager*)central didDisconnectPeripheral:(CBPeripheral*)peripheral error:(NSError*)error {
    (void)central;
    (void)error;
    if(peripheral == self.peripheral) {
        self.cmdCharacteristic = nil;
        self.firmwareCharacteristic = nil;
        self.hardwareCharacteristic = nil;
        self.currentTimeCharacteristic = nil;
        [self emitEvent:2 message:@"Disconnected"];
    }
}

#pragma mark - CBPeripheralDelegate

- (void)peripheral:(CBPeripheral*)peripheral didDiscoverServices:(NSError*)error {
    if(error) {
        [self emitEvent:5 message:[NSString stringWithFormat:@"Discover services error: %@", error]];
        return;
    }
    for(CBService* service in peripheral.services) {
        if([service.UUID isEqual:kAidlabServiceUuid()]) {
            [peripheral discoverCharacteristics:@[kAidlabCmdCharUuid()] forService:service];
        } else if([service.UUID isEqual:kDeviceInfoServiceUuid()]) {
            [peripheral discoverCharacteristics:@[kFirmwareCharUuid(), kHardwareCharUuid()] forService:service];
        } else if([service.UUID isEqual:kCurrentTimeServiceUuid()]) {
            [peripheral discoverCharacteristics:@[kCurrentTimeCharUuid()] forService:service];
        }
    }
}

- (void)peripheral:(CBPeripheral*)peripheral didDiscoverCharacteristicsForService:(CBService*)service error:(NSError*)error {
    if(error) {
        [self emitEvent:5 message:[NSString stringWithFormat:@"Discover characteristics error: %@", error]];
        return;
    }
    for(CBCharacteristic* ch in service.characteristics) {
        if([ch.UUID isEqual:kAidlabCmdCharUuid()]) {
            self.cmdCharacteristic = ch;
            [peripheral setNotifyValue:YES forCharacteristic:ch];
        } else if([ch.UUID isEqual:kFirmwareCharUuid()]) {
            self.firmwareCharacteristic = ch;
            [peripheral readValueForCharacteristic:ch];
        } else if([ch.UUID isEqual:kHardwareCharUuid()]) {
            self.hardwareCharacteristic = ch;
            [peripheral readValueForCharacteristic:ch];
        } else if([ch.UUID isEqual:kCurrentTimeCharUuid()]) {
            self.currentTimeCharacteristic = ch;
            [self writeCurrentTime];
        }
    }
}

- (void)peripheral:(CBPeripheral*)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error {
    (void)peripheral;
    if(error) {
        [self emitEvent:5 message:[NSString stringWithFormat:@"Notify error: %@", error]];
        return;
    }
    if([characteristic.UUID isEqual:kAidlabCmdCharUuid()] && characteristic.isNotifying) {
        [self emitEvent:1 message:@"Connected"];
    }
}

- (void)peripheral:(CBPeripheral*)peripheral didUpdateValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error {
    (void)peripheral;
    if(error) {
        [self emitEvent:5 message:[NSString stringWithFormat:@"Characteristic read/notify error: %@", error]];
        return;
    }
    NSData* value = characteristic.value;
    if(!value) {
        return;
    }

    if([characteristic.UUID isEqual:kAidlabCmdCharUuid()]) {
        if(self.dataCb) {
            self.dataCb(self.context, (const uint8_t*)value.bytes, (int)value.length);
        }
        return;
    }

    NSString* str = [[NSString alloc] initWithData:value encoding:NSUTF8StringEncoding];
    if(!str) {
        str = @"";
    }
    if([characteristic.UUID isEqual:kFirmwareCharUuid()]) {
        self.commandWriteWithoutResponse = str.integerValue >= 4;
        [self emitEvent:3 message:str];
    } else if([characteristic.UUID isEqual:kHardwareCharUuid()]) {
        [self emitEvent:4 message:str];
    }
}

- (void)peripheral:(CBPeripheral*)peripheral didWriteValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error {
    (void)peripheral;
    if([characteristic.UUID isEqual:kAidlabCmdCharUuid()]) {
        self.commandWriteInFlight = NO;
        if(error) {
            [self.commandWriteQueue removeAllObjects];
            [self emitEvent:5 message:[NSString stringWithFormat:@"Write error: %@", error]];
            return;
        }
        [self drainCommandWrites];
        return;
    }
    if(error) {
        [self emitEvent:5 message:[NSString stringWithFormat:@"Write error: %@", error]];
        if([characteristic.UUID isEqual:kCurrentTimeCharUuid()]) {
            [self emitEvent:8 message:[NSString stringWithFormat:@"Time set failed: %@", error]];
        }
        return;
    }
    if([characteristic.UUID isEqual:kCurrentTimeCharUuid()]) {
        [self emitEvent:7 message:@"Time set confirmed"];
    }
}

- (void)peripheralIsReadyToSendWriteWithoutResponse:(CBPeripheral*)peripheral {
    (void)peripheral;
    [self drainCommandWrites];
}

@end

extern "C" {

void* aidlab_ble_create(void* context, aidlab_ble_data_cb data_cb, aidlab_ble_event_cb event_cb,
                        aidlab_ble_discovery_cb discovery_cb) {
    AidlabBleManager* manager = [[AidlabBleManager alloc] initWithContext:context
                                                                   dataCb:data_cb
                                                                  eventCb:event_cb
                                                              discoveryCb:discovery_cb];
    return (__bridge_retained void*)manager;
}

void aidlab_ble_destroy(void* handle) {
    AidlabBleManager* manager = (__bridge_transfer AidlabBleManager*)handle;
    // A Unity domain reload invalidates the managed callbacks while CoreBluetooth may still deliver events, so they
    // are cleared at once and the connection is stopped later on the BLE queue, whose block frees the manager.
    manager.dataCb = nullptr;
    manager.eventCb = nullptr;
    manager.discoveryCb = nullptr;

    dispatch_async(manager.queue, ^{
        [manager stop];
    });
}

bool aidlab_ble_write(void* handle, const uint8_t* data, int size) {
    AidlabBleManager* manager = (__bridge AidlabBleManager*)handle;
    __block BOOL ok = NO;
    dispatch_sync(manager.queue, ^{
        ok = [manager writeBytes:data size:size];
    });
    return ok ? true : false;
}

int aidlab_ble_get_max_write_length(void* handle) {
    AidlabBleManager* manager = (__bridge AidlabBleManager*)handle;
    __block int value = 20;
    dispatch_sync(manager.queue, ^{
        value = [manager maxWriteLen];
    });
    return value;
}

}  // extern "C"
