package com.lukekorth.pebblelocker;

import com.getpebble.android.kit.PebbleKit;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class PebbleLocker extends PreferenceActivity {
	
	private static final int REQUEST_CODE_ENABLE_ADMIN = 1;
	
	private DevicePolicyManager mDPM;
	private ComponentName mDeviceAdmin;
	
	private CheckBoxPreference mAdmin;
	private EditTextPreference mPassword;
	private CheckBoxPreference mEnable;
	private CheckBoxPreference mForceLock;
	
	private SharedPreferences mPrefs;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.main);
		
		mAdmin = (CheckBoxPreference) findPreference("key_enable_admin");
		mPassword = (EditTextPreference) findPreference("key_password");
		mEnable = (CheckBoxPreference) findPreference("key_locker_enable");
		mForceLock = (CheckBoxPreference) findPreference("key_force_lock");
		
		mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
		mDeviceAdmin = new ComponentName(this, CustomDeviceAdminReceiver.class);
		
		mAdmin.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if ((Boolean) newValue) {
                    // Launch the activity to have the user enable our admin.
                    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdmin);
                    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Pebble Locker needs device admin access to lock your device on disconnect");
                    startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
                    
                    // return false - don't update checkbox until we're really active
                    return false;
                } else {
                    mDPM.removeActiveAdmin(mDeviceAdmin);
                    PebbleLocker.this.enableOptions(false);
                    
                    return true;
                }
			}
			
		});
		
		mPassword.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				doResetPassword((String) newValue);
				return true;
			}
		});
		
		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
	}
	
	public void onResume() {
		super.onResume();
		
		if(mDPM.isAdminActive(mDeviceAdmin)) {
			mAdmin.setChecked(true);
			enableOptions(true);
		} else {
			mAdmin.setChecked(false);
			enableOptions(false);
		}
	}
	
	/**
     * This is dangerous, so we prevent automated tests from doing it, and we
     * remind the user after we do it.
     */
    private void doResetPassword(String newPassword) {
        if (alertIfMonkey(this, "You can't reset my password, you are a monkey!")) {
            return;
        }
        
        if(!PebbleKit.isWatchConnected(this) && mPrefs.getBoolean("key_locker_enable", false))
        	mDPM.resetPassword(newPassword, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String message = getString(R.string.reset_password_warning, newPassword);
        builder.setMessage(message);
        builder.setPositiveButton("Don't Forget It!", null);
        builder.show();
    }
	
	private void enableOptions(boolean isEnabled) {
		mPassword.setEnabled(isEnabled);
		mEnable.setEnabled(isEnabled);
		mForceLock.setEnabled(isEnabled);
	}
	
	 /**
     * If the "user" is a monkey, post an alert and notify the caller.  This prevents automated
     * test frameworks from stumbling into annoying or dangerous operations.
     */
    private static boolean alertIfMonkey(Context context, String string) {
        if (ActivityManager.isUserAMonkey()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(string);
            builder.setPositiveButton("Ok", null);
            builder.show();
            return true;
        } else {
            return false;
        }
    }
	
	/**
     * All callbacks are on the UI thread and your implementations should not engage in any
     * blocking operations, including disk I/O.
     */
    public static class CustomDeviceAdminReceiver extends DeviceAdminReceiver {
    	
        @Override
        public void onEnabled(Context context, Intent intent) {
        	// intentionally left blank
        }

        @Override
        public CharSequence onDisableRequested(Context context, Intent intent) {
        	// intentionally left blank
        	return null;
        }

        @Override
        public void onDisabled(Context context, Intent intent) {
        	// intentionally left blank
        }

        @Override
        public void onPasswordChanged(Context context, Intent intent) {
        	// intentionally left blank
        }

        @Override
        public void onPasswordFailed(Context context, Intent intent) {
        	Toast.makeText(context, "Password change failed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPasswordSucceeded(Context context, Intent intent) {
        	// intentionally left blank
        }

        @Override
        public void onPasswordExpiring(Context context, Intent intent) {
            // intentionally left blank
        }
    }

}

@@ -2978,24 +2978,406 @@
 %09%7D%0A%09%09%7D);%0A%09%09%0A
+%09%09mEnable.setOnPreferenceChangeListener(new OnPreferenceChangeListener() %7B%0A%09%09%09@Override%0A%09%09%09public boolean onPreferenceChange(Preference preference, Object newValue) %7B%0A%09%09%09%09if(Boolean.parseBoolean(newValue.toString()))%0A%09%09%09%09%09showAlert(%22Pebble Locker is enabled, please set your password%22);%0A%09%09%09%09else%0A%09%09%09%09%09mPrefs.edit().putString(%22key_password%22, %22%22);%0A%09%09%09%09%0A%09%09%09%09return true;%0A%09%09%09%7D%0A%09%09%7D);%0A%09%09%0A
 %09%09mPrefs = P
@@ -4593,16 +4593,232 @@
 );%0A%09%7D%0A%09%0A
+%09private void showAlert(String string) %7B%0A%09%09AlertDialog.Builder builder = new AlertDialog.Builder(this);%0A        builder.setMessage(string);%0A        builder.setPositiveButton(%22Ok%22, null);%0A        builder.show();%0A%09%7D%0A%09%0A
 %09 /**%0A  
@@ -5008,23 +5008,16 @@
 private 
-static 
 boolean 
@@ -5127,188 +5127,24 @@
     
-AlertDialog.Builder builder = new AlertDialog.Builder(context);%0A            builder.setMessage(string);%0A            builder.setPositiveButton(%22Ok%22, null);%0A            builder.show(
+showAlert(string
 );%0A 

Add handling for enabling and disabling app