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

#import "IoTMediaItem.h"
#import "IoTResourceAttributes.h"

@interface IoTMediaItem()

@property (nonatomic, strong) NSMutableArray<NSString *> *customHTTPHeaders;

@end

@implementation IoTMediaItem

- (instancetype)init
{
    self = [super init];
    if (self) {
        self->_streamURL = @"";
        self->_thumbnailURL = @"";
        self->_title = @"";
        self->_artist = @"";
        self->_album = @"";
        self->_genre = @"";
        self->_country = @"";
        self->_duration = 0;
        self->_userData = @"";
    }
    return self;
}

- (instancetype)initWithAttr:(IoTPlayItemAttr *)attr
{
    NSParameterAssert(nil != attr);
    self = [self init];
    if (self) {
        self->_streamURL = attr.url ?: @"";
        self->_thumbnailURL = attr.thumbnailUrl ?: @"";
        self->_title = attr.title ?: @"";
        self->_artist = attr.artist ?: @"";
        self->_album = attr.album ?: @"";
        self->_genre = attr.genre ?: @"";
        self->_country = [self userData:attr.userData valueForKey:@"country"];
        self->_duration = attr.durationMsecs;
    }
    return self;
}

- (void)copyToAttr:(IoTPlayItemAttr *)attr
{
    attr.url = self.streamURL ?: @"";
    attr.thumbnailUrl = self.thumbnailURL ?: @"";
    attr.title = self.title ?: @"";
    attr.artist = self.artist ?: @"";
    attr.album = self.album ?: @"";
    attr.genre = self.genre ?: @"";
    attr.durationMsecs = self.duration;

    NSMutableArray<IoTVariantHelperAttr *> *array = [NSMutableArray array];
    if (self.country.length > 0) {
        IoTVariantHelperAttr *helper = [[IoTVariantHelperAttr alloc] initWithStateSyncQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)];
        helper.key = @"country";
        helper.value = self.country;
        [array addObject:helper];
    }
    attr.userData = array;
}

- (BOOL)isEmpty
{
    return (([self.title length] == 0) &&
            ([self.artist length] == 0) &&
            ([self.album length] == 0) &&
            ([self.streamURL length] == 0));
}

- (NSString *)userData:(NSArray <IoTVariantHelperAttr *> *)userData valueForKey:(NSString *)key
{
    __block NSString *value = @"";
    [userData enumerateObjectsUsingBlock:^(IoTVariantHelperAttr * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.key isEqualToString:key]) {
            value = obj.key;
            *stop = YES;
        }
    }];
    return value;
}

@end
