// #import <AVFoundation/AVFoundation.h>
#import <CoreLocation/CoreLocation.h>
#import <React/RCTConvert.h>
#import "RNMyNativeModule.h"

/**
 ** see more about ios corelocation service: https://developer.apple.com/documentation/corelocation/cllocationmanager
 **/
@interface RNMyNativeModule () <CLLocationManagerDelegate>
    @property (strong, nonatomic) CLLocationManager *locationManager;
@end

@implementation RNMyNativeModule{
      BOOL hasListeners;
}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
@synthesize locationManager;
-(instancetype) init {
    if(self = [super init]){
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy =kCLLocationAccuracyBest;
        self.locationManager.pausesLocationUpdatesAutomatically = NO;

    }
    [self.locationManager startUpdatingLocation];
    return self;
}
RCT_EXPORT_MODULE()

/*
 * test call back
 */

RCT_EXPORT_METHOD(helloworld: (RCTResponseSenderBlock) callback) {
    NSString *hello = [NSString stringWithFormat:@"Hello world, this messeage sender from native ios"];
    callback(@[hello]);
}

// test promise, neu error thi reject ra 1 object(ben JS)
RCT_REMAP_METHOD(getTimeStamp,
                 resolve:(RCTPromiseResolveBlock)resolve
                 reject:(RCTPromiseRejectBlock)reject) {
    @try {
        NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
        // NSTimeInterval is defined as double
        NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp];
        resolve(@[timeStampObj]);

    }@catch(NSException *exception) {
        NSMutableDictionary *info = [NSMutableDictionary dictionary];
        [info setValue:exception.name forKey:@"ExceptionName"];
        [info setValue:exception.reason forKey:@"ExceptionReason"];
        [info setValue:exception.callStackReturnAddresses forKey:@"ExceptionCallStackReturnAddresses"];
        [info setValue:exception.callStackSymbols forKey:@"ExceptionCallStackSymbols"];
        [info setValue:exception.userInfo forKey:@"ExceptionUserInfo"];

        NSError *error = [[NSError alloc] initWithDomain:@"com.example.myApp" code:4 userInfo:info];
        reject([info valueForKey:@"ExceptionName"], [info valueForKey:@"ExceptionReason"], error);
    }
}

/**
 ** Brigde location
 **/
// returm status auth
//RCT_EXPORT_METHOD(initLocation){
//    locationManager = [[CLLocationManager alloc] init];
//    [locationManager setDelegate: self];
//    [locationManager setDesiredAccuracy: kCLLocationAccuracyBest];
//    if([loca])
//
//}

RCT_EXPORT_METHOD(checkPermissions:(RCTResponseSenderBlock)callback)
{
    callback(@[[self authStatusToString:[CLLocationManager authorizationStatus]]]);
}

RCT_EXPORT_METHOD(checkEnableLocationService:(RCTResponseSenderBlock) callback){
    BOOL isEnable= [CLLocationManager locationServicesEnabled];
    callback(@[[NSNull null], @(isEnable)]);
}

RCT_EXPORT_METHOD(requestWhenInUseAuth){
    [self.locationManager requestWhenInUseAuthorization];
}

RCT_EXPORT_METHOD(requestAlwaysAuth){
    [self.locationManager requestAlwaysAuthorization];
}
/***************************/
/****========EVENT ======**/
/***************************/
// override function to do something in case you want to use event emitter
- (void)startObserving {
    hasListeners = YES;
}

// override function to do something in case you want to use event emitter
- (void)stopObserving {
    hasListeners = NO;
}

/**
 * register event name
 * NOTE: Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread
 * Events are powerful, because they allow us to change React Native components without needing a reference to them
 */
- (NSArray<NSString *> *)supportedEvents {
    return @[@"addEvent", @"authStatusDidChange", @"didUpdateLocation"];
}

//RCT_REMAP_METHOD(addEvent,
//                 name:(NSString *)name
//                 details:(NSDictionary *)details)
//{
//    if(hasListeners) {
//        NSString *value = [RCTConvert NSString:details[@"value"]];
//        NSString *time = [RCTConvert NSString:details[@"time"]];
//        [self sendEventWithName:@"addEvent" body:@{@"value": value, @"time": time}];
//    } else {
//        NSLog(@"You did not registered any event/listener");
//    }
//}
//emit khi trạng thái của event thay đổi overrive location core
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    NSString *statusName = [self authStatusToString:status];
    NSLog(@"co su kien ne :v");
    [self sendEventWithName:@"authStatusDidChange" body:statusName];
}

// emit khi trạng thái của location thay đổi

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    NSDictionary *locationData = @{
                                   @"coords": @{
                                           @"latitude": @(location.coordinate.latitude),
                                           @"longitude": @(location.coordinate.longitude),
                                           @"course": @(location.course),
                                           @"speed": @(location.speed)
                                           },
                                    @"timestamp": @([location.timestamp timeIntervalSince1970] * 1000)
                                   };
    NSLog(@"======== location %@", locationData);
     [self sendEventWithName:@"didUpdateLocation" body: locationData];
}



-(NSString *) authStatusToString:(CLAuthorizationStatus)authStatus
{
    switch (authStatus) {
        case kCLAuthorizationStatusAuthorizedAlways:
            return @"authorizedAlways";

        case kCLAuthorizationStatusAuthorizedWhenInUse:
            return @"authorizedWhenInUse";

        case kCLAuthorizationStatusDenied:
            return @"denied";

        case kCLAuthorizationStatusNotDetermined:
            return @"notDetermined";

        case kCLAuthorizationStatusRestricted:
            return @"restricted";
    }
}


@end



