/*
 * Copyright (C) 2015 Willi Ye
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.grarak.kerneladiutor.services;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import com.grarak.kerneladiutor.MainActivity;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.kernel.Screen;

/**
 * Created by willi on 08.03.15.
 */
public class AutoHighBrightnessModeService extends Service {
    float lux = 0, curlux = 0, lux1 = 0, lux2 = 0;
    public static int LuxThresh = 50000;
    public static boolean HBM_Widget_Toggled = false;

    private SensorManager sMgr;
    Sensor light;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterAutoHBMReceiver(getApplicationContext());
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT > 19 && pm.isInteractive()) {
            deactivateLightSensorRead();
        } else if (Build.VERSION.SDK_INT < 20 ) {
            deactivateLightSensorRead();
        }
    }

    private void init() {
        registerAutoHBMReceiver(getApplicationContext());
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT > 19 && pm.isInteractive()) {
            activateLightSensorRead();
        } else if (Build.VERSION.SDK_INT < 20 ) {
            activateLightSensorRead();
        }
    }

    public void activateLightSensorRead() {
        sMgr = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);

        light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

        sMgr.registerListener(_SensorEventListener, light, SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void deactivateLightSensorRead() {
        sMgr.unregisterListener(_SensorEventListener);
    }

    SensorEventListener _SensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (!HBM_Widget_Toggled) {
                if (Screen.isScreenAutoHBMSmoothingActive(MainActivity.context)) {
                    // This should average the last 3 lux values
                    // This will cause some delay in autohbm actually working as the values initialize at 0
                    lux2 = lux1;
                    lux1 = curlux;
                    curlux = event.values[0];
                    lux = (curlux + lux1 + lux2) / 3;
                } else {
                    lux = event.values[0];
                }
                if (lux >= LuxThresh && !Screen.isScreenHBMActive()) {
                    Log.i("Kernel Adiutor: ", "AutoHBMService Activating HBM: received LUX value: " + lux + " Threshold: " + LuxThresh);
                    Screen.activateScreenHBM(true, getApplicationContext());
                }
                if (lux < LuxThresh && Screen.isScreenHBMActive()) {
                    Log.i("Kernel Adiutor: ", "De-Activation: AutoHBMService: received LUX value: " + lux + " Threshold: " + LuxThresh);
                    Screen.activateScreenHBM(false, getApplicationContext());
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

    private BroadcastReceiver AutoHBMreceiver = null;

    private void registerAutoHBMReceiver(Context context) {
        final IntentFilter autohbmfilter = new IntentFilter();
        /** System Defined Broadcast */
        autohbmfilter.addAction(android.content.Intent.ACTION_SCREEN_ON);
        autohbmfilter.addAction(android.content.Intent.ACTION_SCREEN_OFF);

        AutoHBMreceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, android.content.Intent intent) {
                String strAction = intent.getAction();
                if (strAction.equals(android.content.Intent.ACTION_SCREEN_OFF)) {
                    HBM_Widget_Toggled = false;
                    if (Utils.getBoolean("AutoHBM", false, getApplicationContext())) {
                        LuxThresh = Utils.getInt("AutoHBM_Threshold", 1500, getApplicationContext());
                        deactivateLightSensorRead();
                    }
                }

                if (strAction.equals(android.content.Intent.ACTION_SCREEN_ON)) {
                    HBM_Widget_Toggled = false;
                    if (Utils.getBoolean("AutoHBM", false, getApplicationContext())) {
                        LuxThresh = Utils.getInt("AutoHBM_Threshold", 1500, getApplicationContext());
                        activateLightSensorRead();
                    }
                }
            }
        };

        context.registerReceiver(AutoHBMreceiver, autohbmfilter);
    }

    private void unregisterAutoHBMReceiver(Context context) {
        int apiLevel = Build.VERSION.SDK_INT;

        if (apiLevel >= 7) {
            try {
                context.unregisterReceiver(AutoHBMreceiver);
            } catch (IllegalArgumentException e) {
                AutoHBMreceiver = null;
            }
        } else {
            AutoHBMreceiver = null;
        }
    }
}


@@ -3056,51 +3056,8 @@
 ) %7B%0A
-            if (!HBM_Widget_Toggled) %7B%0A    
     
@@ -3139,36 +3139,32 @@
                 
-    
 // This should a
@@ -3200,36 +3200,32 @@
                 
-  
-  
 // This will cau
@@ -3312,20 +3312,16 @@
         
-    
 lux2 = l
@@ -3341,20 +3341,16 @@
         
- 
-   
 lux1 = c
@@ -3356,20 +3356,16 @@
 curlux;%0A
-    
         
@@ -3410,28 +3410,24 @@
             
-    
 lux = (curlu
@@ -3456,28 +3456,24 @@
             
-   
- 
 %7D else %7B%0A   
@@ -3461,36 +3461,32 @@
        %7D else %7B%0A
-    
                 
@@ -3512,37 +3512,72 @@
 0%5D;%0A            
-    %7D
+%7D%0A            if (!HBM_Widget_Toggled) %7B
 %0A               

Fix where it's checking the variable