//
//  RNDUBattery.m
//  RNDUBattery
//
//  Created by Sara Federico on 07/09/2019
//

#import <React/RCTAssert.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>

#import "RNDUBattery.h"

@implementation RNDUBattery
{
  BOOL _isObserving;
}

RCT_EXPORT_MODULE()

- (instancetype)init
{
    if((self = [super init])) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
        });

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(batteryLevelChanged:)
                                                     name:UIDeviceBatteryLevelDidChangeNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(batteryLevelChanged:)
                                                     name:UIDeviceBatteryStateDidChangeNotification
                                                   object:nil];
    }
    return self;
}

-(void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+(BOOL)requiresMainQueueSetup
{
  return YES;
}

-(void)startObserving
{
  _isObserving = YES;
}

-(void)stopObserving
{
  _isObserving = NO;
}

-(dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

-(id)getBatteryStatus
{
  UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;

  bool isCharging = batteryState == UIDeviceBatteryStateCharging;
  float batteryLevel = [UIDevice currentDevice].batteryLevel;
  float percentLevel = batteryLevel * 100;

  NSMutableDictionary* batteryInfo = [NSMutableDictionary dictionaryWithCapacity:2];

  [batteryInfo setObject:[NSNumber numberWithBool:isCharging] forKey:@"isCharging"];
  [batteryInfo setObject:[NSNumber numberWithFloat:percentLevel] forKey:@"chargePercent"];

  return @{
          @"battery": batteryInfo
          };
}

-(void)batteryLevelChanged:(NSNotification*)notification
{
  NSDictionary* batteryInfo = [self getBatteryStatus];
  [self sendEventWithName:@"RNDUBattery" body:batteryInfo];
}

RCT_EXPORT_METHOD(getCurrentState:(RCTPromiseResolveBlock)resolve
                  reject:(__unused RCTPromiseRejectBlock)reject)
{
  if (self->_isObserving) {
    resolve(self.getBatteryStatus)
  }
}

@end
