//
//  BluestackAdsCommon.m
//  @azerion/bluestack-sdk-react-native
//
//  Created by moin on 04/06/2024.
//

#import "BluestackAdsCommon.h"
#import <BlueStackSDK/MNGAdsSDKFactory.h>
#import <CoreLocation/CoreLocation.h>

@implementation BluestackAdsCommon

static NSString *BSUStringFromUTF8String(const char *bytes) { return bytes ? @(bytes) : nil; }

+ (MNGPreference *)getMNGPreference:(NSString *)preferenceJSON {

    MNGPreference *preference = [[MNGPreference alloc] init];
    
    NSError *error;
    NSData *jsonData = [preferenceJSON dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    
    if (error) {
        NSLog(@"Error parsing JSON: %@", error.localizedDescription);
        return nil;
    }
    
    //Gender
    NSString *gender = jsonDict[@"gender"];
    if ([gender isEqualToString:@"Male"]) {
        preference.gender = (MNGGender)1;
    } else if ([gender isEqualToString:@"Female"]) {
        preference.gender = (MNGGender)2;
    } else {
        preference.gender = (MNGGender)0; // default to unknown
    }
        
    preference.age = [jsonDict[@"age"] integerValue];
    preference.language = jsonDict[@"language"];
    preference.contentUrl = jsonDict[@"contentUrl"];
    preference.keyWord = jsonDict[@"keyword"];
        
    NSDictionary *locationDict = jsonDict[@"location"];
    NSInteger consentFlag = [jsonDict[@"consentFlag"] integerValue];
    
    //Location
    if (locationDict) {
        double latitude = [locationDict[@"latitude"] doubleValue];
        double longitude = [locationDict[@"longitude"] doubleValue];
        //NSString *provider = locationDict[@"provider"];
        
        if (latitude && longitude) {
            
            [preference setLocationPreferences:[[CLLocation alloc] initWithLatitude:latitude longitude:longitude] WithConsentFlag:consentFlag];
        }
    }
      
    return preference;
    
}

@end
