#import "CDVSystemControls.h"
#import <UIKit/UIKit.h>

@implementation CDVSystemControls {
    CDVInvokedUrlCommand* batteryCallback;
    BOOL isMonitoring;
}

- (void)getBatteryStatus:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        UIDevice* device = [UIDevice currentDevice];
        device.batteryMonitoringEnabled = YES;
        
        float batteryLevel = device.batteryLevel;
        UIDeviceBatteryState batteryState = device.batteryState;
        
        BOOL isPlugged = (batteryState == UIDeviceBatteryStateCharging || 
                         batteryState == UIDeviceBatteryStateFull);
        
        NSDictionary* result = @{
            @"level": @(batteryLevel * 100),
            @"isPlugged": @(isPlugged)
        };
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK 
                                                          messageAsDictionary:result];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)startBatteryMonitoring:(CDVInvokedUrlCommand*)command {
    if (isMonitoring) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR 
                                                              messageAsString:@"Battery monitoring is already active"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    
    batteryCallback = command;
    isMonitoring = YES;
    
    UIDevice* device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryStateDidChange:)
                                                 name:UIDeviceBatteryStateDidChangeNotification
                                               object:device];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryLevelDidChange:)
                                                 name:UIDeviceBatteryLevelDidChangeNotification
                                               object:device];
    
    // Send initial battery status
    [self getBatteryStatus:command];
}

- (void)stopBatteryMonitoring:(CDVInvokedUrlCommand*)command {
    if (!isMonitoring) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR 
                                                              messageAsString:@"Battery monitoring is not active"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    
    UIDevice* device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = NO;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIDeviceBatteryStateDidChangeNotification 
                                                  object:device];
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIDeviceBatteryLevelDidChangeNotification 
                                                  object:device];
    
    isMonitoring = NO;
    batteryCallback = nil;
    
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)batteryStateDidChange:(NSNotification*)notification {
    if (batteryCallback) {
        UIDevice* device = [UIDevice currentDevice];
        float batteryLevel = device.batteryLevel;
        UIDeviceBatteryState batteryState = device.batteryState;
        
        BOOL isPlugged = (batteryState == UIDeviceBatteryStateCharging || 
                         batteryState == UIDeviceBatteryStateFull);
        
        NSDictionary* result = @{
            @"level": @(batteryLevel * 100),
            @"isPlugged": @(isPlugged),
            @"event": @"batterystatus"
        };
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK 
                                                          messageAsDictionary:result];
        pluginResult.keepCallback = @YES;
        [self.commandDelegate sendPluginResult:pluginResult callbackId:batteryCallback.callbackId];
    }
}

- (void)batteryLevelDidChange:(NSNotification*)notification {
    if (batteryCallback) {
        UIDevice* device = [UIDevice currentDevice];
        float batteryLevel = device.batteryLevel;
        UIDeviceBatteryState batteryState = device.batteryState;
        
        BOOL isPlugged = (batteryState == UIDeviceBatteryStateCharging || 
                         batteryState == UIDeviceBatteryStateFull);
        
        NSDictionary* result = @{
            @"level": @(batteryLevel * 100),
            @"isPlugged": @(isPlugged),
            @"event": @"batterystatus"
        };
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK 
                                                          messageAsDictionary:result];
        pluginResult.keepCallback = @YES;
        [self.commandDelegate sendPluginResult:pluginResult callbackId:batteryCallback.callbackId];
    }
}

- (void)getBrightness:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        float brightness = [UIScreen mainScreen].brightness;
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK 
                                                              messageAsDouble:brightness];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)setBrightness:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        float brightness = [[command.arguments objectAtIndex:0] floatValue];
        
        // Clamp brightness between 0.0 and 1.0
        brightness = MAX(0.0f, MIN(1.0f, brightness));
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIScreen mainScreen].brightness = brightness;
            
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        });
    }];
}

- (void)getSystemBrightness:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        float brightness = [UIScreen mainScreen].brightness;
        int systemBrightness = (int)(brightness * 255);
        
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK 
                                                              messageAsInt:systemBrightness];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)setSystemBrightness:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        int brightness = [[command.arguments objectAtIndex:0] intValue];
        
        // Clamp brightness between 0 and 255
        brightness = MAX(0, MIN(255, brightness));
        float normalizedBrightness = brightness / 255.0f;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIScreen mainScreen].brightness = normalizedBrightness;
            
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        });
    }];
}

- (void)dealloc {
    if (isMonitoring) {
        UIDevice* device = [UIDevice currentDevice];
        device.batteryMonitoringEnabled = NO;
        
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
}

@end 