package unknownmoon.cryforlight;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

public class LightService extends Service {
    private final int NOTIFICATION_ID = 1;
    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;
    private Notification.Builder mBuilder;
    private Toast mToast = null;

    public LightService() {
    }

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

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_FOREGROUND);
        thread.start();

        // Get the HandlerThread's Looper and use it for our Handler
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // For each start request, send a message to start a job and deliver the
        // start ID so we know which request we're stopping when we finish the job
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        mServiceHandler.sendMessage(msg);

        mBuilder = new Notification.Builder(getApplicationContext());

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Cry for Light is on!")
                .setContentText("Let's keep the light on!")
                .setAutoCancel(true)
//                .setSound(Uri.parse("content://media/internal/audio/media/29")) // TODO
                .setContentIntent(pendingIntent);

        startForeground(NOTIFICATION_ID, mBuilder.build());

        broadcastStarted();

        // If we get killed, after returning from here, restart
        return START_STICKY;
    }

    protected void showMsg(String msg, int duration) {
        if (mToast != null) {

            // dismiss the previous message if exists.
            mToast.cancel();
        }

        mToast = Toast.makeText(getApplicationContext(), msg, duration);
        mToast.show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        showMsg("Service off", Toast.LENGTH_SHORT);
        broadcastStopped();
    }

    private void broadcastStarted() {
        // Answer the started
        Intent notifyStartedIntent = new Intent("from-service");
        notifyStartedIntent.putExtra("SERVICE_STARTED", true);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(notifyStartedIntent);
    }

    private void broadcastStopped() {
        // Answer the started
        Intent notifyStoppedIntent = new Intent("from-service");
        notifyStoppedIntent.putExtra("SERVICE_STARTED", false);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(notifyStoppedIntent);
    }

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            showMsg("Service on", Toast.LENGTH_SHORT);
//            stopSelf(msg.arg1);
        }
    }
}

@@ -145,22 +145,207 @@
 content.
-Intent
+Context;%0Aimport android.content.Intent;%0Aimport android.hardware.Sensor;%0Aimport android.hardware.SensorEvent;%0Aimport android.hardware.SensorEventListener;%0Aimport android.hardware.SensorManager
 ;%0Aimport
@@ -554,32 +554,57 @@
 oadcastManager;%0A
+import android.util.Log;%0A
 import android.w
@@ -779,24 +779,66 @@
 iceHandler;%0A
+    private SensorHandler mSensorHandler;%0A
     private 
@@ -2638,24 +2638,636 @@
 ngIntent);%0A%0A
+        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);%0A        Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);%0A%0A        // check sensor available in devise. if available then get reading%0A        if (lightSensor == null) %7B%0A            showMsg(%22No light sensor :(%22, Toast.LENGTH_SHORT);%0A        %7D else %7B%0A            float max = lightSensor.getMaximumRange();%0A            mSensorHandler = new SensorHandler();%0A            sensorManager.registerListener(mSensorHandler,%0A                    lightSensor, SensorManager.SENSOR_DELAY_NORMAL);%0A%0A        %7D%0A%0A
         star
@@ -3998,24 +3998,235 @@
 Destroy();%0A%0A
+        if (mSensorHandler != null) %7B%0A            SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);%0A            sensorManager.unregisterListener(mSensorHandler);%0A        %7D%0A%0A
         show
@@ -5177,16 +5177,16 @@
 SHORT);%0A
-
 //      
@@ -5226,11 +5226,468 @@
  %7D%0A    %7D
+%0A%0A    private final class SensorHandler implements SensorEventListener %7B%0A%0A        @Override%0A        public void onSensorChanged(SensorEvent event) %7B%0A            if (event.sensor.getType() == Sensor.TYPE_LIGHT) %7B%0A                float currentReading = event.values%5B0%5D;%0A%0A                Log.d(%22L%22, String.valueOf(currentReading));%0A            %7D%0A        %7D%0A%0A        @Override%0A        public void onAccuracyChanged(Sensor sensor, int accuracy) %7B%0A%0A        %7D%0A    %7D
 %0A%7D%0A

Read light sensor value.