//
// © 2018-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

#import "IoTDeviceState.h"
#import "IoTResourceAttributes.h"
#import "IoTGlobals.h"

#define GETTER_SYNCHRONIZED(type,property) \
- (type)property \
{ \
dispatch_assert_queue_not(self.syncQueue); \
__block type ret; \
dispatch_sync(self.syncQueue, ^{ \
ret = self->_##property; \
}); \
return ret; \
}

#define SETTER_SYNCHRONIZED(type,method,property,assigner) \
- (void)method:(type)property \
{ \
makeWeak(self) \
dispatch_barrier_async(self.syncQueue, ^{ \
makeStrongAndReturnIfNil(self) \
self->_##property = assigner; \
}); \
}

@interface IoTDeviceState()

@property (nonatomic,strong, readonly) dispatch_queue_t syncQueue;

@end

@implementation IoTDeviceState {
    IoTSystemAttr *_systemAttr;
    IoTBluetoothState *_bluetoothState;
    IoTNetworkAttr *_networkAttr;
    IoTVoiceUIAttr *_voiceAttr;
    IoTZigbeeState *_zigbeeState;
}

- (instancetype)initWithStateSyncQueue:(dispatch_queue_t)syncQueue
{
    self = [super init];
    if (self) {
        self->_syncQueue = syncQueue;
        self->_systemAttr = [[IoTSystemAttr alloc] initWithStateSyncQueue:self->_syncQueue];
        self->_bluetoothState = [[IoTBluetoothState alloc] init];
        [self->_bluetoothState updateWithAttribute:[[IoTBluetoothAttr alloc] initWithStateSyncQueue:self->_syncQueue]];
        self->_networkAttr = [[IoTNetworkAttr alloc] initWithStateSyncQueue:self->_syncQueue];
        self->_voiceAttr = [[IoTVoiceUIAttr alloc] initWithStateSyncQueue:self->_syncQueue];
        self->_zigbeeState = [[IoTZigbeeState alloc] init];
        [self->_zigbeeState updateWithAttribute:[[IoTZigbeeAttr alloc] initWithStateSyncQueue:self->_syncQueue]];
    }
    return self;
}

GETTER_SYNCHRONIZED(IoTSystemAttr *,systemAttr)
GETTER_SYNCHRONIZED(IoTBluetoothState *,bluetoothState)
GETTER_SYNCHRONIZED(IoTNetworkAttr *,networkAttr)
GETTER_SYNCHRONIZED(IoTVoiceUIAttr *,voiceAttr)
GETTER_SYNCHRONIZED(IoTZigbeeState *,zigbeeState)


SETTER_SYNCHRONIZED(IoTSystemAttr *, setSystemAttr, systemAttr, systemAttr)
SETTER_SYNCHRONIZED(IoTNetworkAttr *,setNetworkAttr,networkAttr,networkAttr)
SETTER_SYNCHRONIZED(IoTVoiceUIAttr *,setVoiceAttr,voiceAttr,voiceAttr)

@end
