//
//  BTLEDeivceModel.m
//  OneCable
//
//  Created by KaRam Kim on 2017. 5. 17..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "BTLEDeivceModel.h"
#import "CBUUID+String.h"

@interface BTLEDeivceModel () {
//    CBPeripheral *peripheralRef;
//    NSDictionary *advertisementData;
//    CBCentralManager *manager;
    
    NSString *advServices;
    NSString *brcData;
}
@end

@implementation BTLEDeivceModel

- (int)txPower {
    if ([_advertisementData objectForKey:CBAdvertisementDataTxPowerLevelKey]) {
        return [[_advertisementData objectForKey:CBAdvertisementDataTxPowerLevelKey] intValue];
    }
    return -1;
}

- (NSString*)advertisedServices {
    if (advServices) return advServices;
    
    NSMutableString *str = [[NSMutableString alloc] init];
    if ([_advertisementData objectForKey:CBAdvertisementDataServiceUUIDsKey]) {
        
        [str appendString:@"Services: "];
        NSArray *services = [_advertisementData objectForKey:CBAdvertisementDataServiceUUIDsKey];
        if ([services count]) {
            for (CBUUID *serviceUUID in services) {
                [str appendFormat:@"%@, ", [serviceUUID representativeString]];
            }
            [str appendString:@"xxx"];
            [str replaceOccurrencesOfString:@", xxx" withString:@"" options:0 range:NSMakeRange(0, [str length])];
            
            advServices = str;
            
        } else {
            advServices = @"No advertised services";
        }
    } else {
        advServices = @"No advertised services";
    }
    return advServices;
}

- (int)channel {
    if ([_advertisementData objectForKey:@"kCBAdvDataChannel"])
        return [[_advertisementData objectForKey:@"kCBAdvDataChannel"] intValue];
    
    return -1;
}

- (BOOL)isConnectable {
    return [[_advertisementData objectForKey:CBAdvertisementDataIsConnectable] boolValue];
}

- (NSString*)name {
    NSString *deviceName = nil;
    
    if ((deviceName = [_peripheralRef name]) && [deviceName length]) {
        return deviceName;
    } else if ((deviceName = [_advertisementData objectForKey:CBAdvertisementDataLocalNameKey]) && [deviceName length]) {
        return deviceName;
    }
    return @"<no name>";
}

- (NSString*)broadcastData {
    if (brcData) return brcData;
    
    if ([_advertisementData objectForKey:CBAdvertisementDataManufacturerDataKey]) {
        NSString *raw = [[_advertisementData objectForKey:CBAdvertisementDataManufacturerDataKey] description];
        raw = [raw stringByReplacingOccurrencesOfString:@"<" withString:@""];
        raw = [raw stringByReplacingOccurrencesOfString:@">" withString:@""];
        brcData = [NSString stringWithFormat:@"Broadcasted data: 0x%@", raw];
    } else {
        brcData = @"No broadcasted data";
    }
    return brcData;
}


-(NSArray*)getServiceList
{
    return _peripheralRef.services;
}

@end


@implementation BLEWLanModel
@end

@implementation BLEWLanListModel
@end

