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

#import "IoTWrappedRepresentation.h"
#include <OCApi.h>
#include <OCPlatform.h>

@implementation IoTWrappedRepresentation
{
    OC::OCRepresentation _rep;
}

+ (instancetype)emptyWrapper
{
    return [[self alloc] init];
}

+ (instancetype)wrapperWithRepresentation:(OC::OCRepresentation)rep
{
    IoTWrappedRepresentation *me = [[self alloc] init];
    me->_rep = rep;
    return me;
}
- (OC::OCRepresentation)representation
{
    return _rep;
}

- (NSArray<NSString *> *)keysInRep:(OC::OCRepresentation)rep
{
    const std::map<std::string, OC::AttributeValue>& attributes = rep.getValues();
    NSMutableArray<NSString *> *keys = [[NSMutableArray alloc] init];
    for (auto element : attributes) {
        [keys addObject:[NSString stringWithUTF8String:element.first.c_str()]];
    }
    return [keys copy];
}

- (BOOL)isEmpty
{
    return _rep.numberOfAttributes() == 0;
}

- (NSArray<NSString *> *)keys
{
    return [self keysInRep:_rep];
}

- (NSArray<NSString *> *)subKeysForKey:(NSString *)key
{
    std::string cppKey = [key UTF8String];
    if (!_rep.hasAttribute(cppKey)) {
        return @[];
    }
    OC::OCRepresentation subRep = _rep[cppKey];
    return [self keysInRep:subRep];
}


- (int)intValueForKey:(NSString *)key
{
    std::string cppKey = [key UTF8String];
    if (_rep.hasAttribute(cppKey)) {
        return _rep[cppKey];
    } else {
        return 0;
    }
}

- (double)doubleValueForKey:(NSString *)key
{
    std::string cppKey = [key UTF8String];
    if (_rep.hasAttribute(cppKey)) {
        return _rep[cppKey];
    } else {
        return 0;
    }
}

- (NSString *)stringValueForKey:(NSString *)key
{
    std::string cppKey = [key UTF8String];
    if (_rep.hasAttribute(cppKey)) {
        std::string cppStr = _rep[cppKey];
        return [NSString stringWithUTF8String:cppStr.c_str()];
    } else {
        return @"";
    }
}

- (BOOL)boolValueForKey:(NSString *)key
{
    std::string cppKey = [key UTF8String];
    if (_rep.hasAttribute(cppKey)) {
        return _rep[cppKey] ? YES : NO;
    } else {
        return NO;
    }
}

@end
