(function() {
    'use strict';

    var oneKeyApp = angular.module('oneKeyApp');

    oneKeyApp.controller('devicesController', [
        '$scope', '$rootScope', '$timeout', '$modal', '$log', 'localize', 'notify', 'userSettings',

        function notificationsController($scope, $rootScope, $timeout, $modal, $log, localize, notify, userSettings) {
            $scope.devices = [];
            $scope.loading = true;
            $scope.saving = false;

            $scope.messages = {
                success: localize('messages', 'updatedDeviceSettings'),
                error: localize('messages', 'unexpectedError')
            };

            $scope.load = function () {
                var devices = userSettings.getDevices(function () {
                    $scope.loading = false;
                });

                if (devices) {
                    $scope.devices = devices;
                }
            };

            $scope.toggleDevice = function (device) {
                var state = device.isDisabled;
                if (state) {
                    state &= false;
                } else {
                    state |= true;
                }

                device.isDisabled = state;
            };

            $scope.update = function (device) {
                function success() {
                    notify.success($scope.messages.success.value);
                    $scope.saving = false;
                }

                function error() {
                    notify.error($scope.messages.error.value);
                    $scope.saving = false;
                }

                if ($scope.loading || $scope.saving) {
                    return;
                }

                $scope.saving = true;
                $scope.toggleDevice(device);
                userSettings.updateDevice(device, success, error);
            };

            $scope.initialize = function() {
                $scope.load();
            };
        }
    ]);
}());
(function () {
	'use strict';

	var oneKeyApp = angular.module('oneKeyApp');

	oneKeyApp.controller('notificationsController', [
		'$scope', '$rootScope', 'localize', 'notify', 'userSettings', 'featureToggle',

		function notificationsController($scope, $rootScope, localize, notify, userSettings, featureToggle) {
			$scope.loading = true;
			$scope.saving = false;
			$scope.notifications = null;
			$scope.emails = [];
            $scope.additional = '';
            $scope.enableGeofence = false;
            featureToggle.getAll()
                .then(function (response) {
                    $scope.enableGeofence = response.geofence;
                });
			function distinct(emails) {
				if (emails) {
					return emails.filter(function (value, index) { return emails.indexOf(value) === index; });
				}
				return [];
			}

			$scope.messages = {
				success: localize('messages', 'notificationSettingsHaveBeenSaved'),
				validation: localize('messages', 'notificationSettingsHaveNotBeenSaved'),
				existingEmail: localize('messages', 'EmailAlreadyExists'),
				error: localize('messages', 'unexpectedError'),
				invalidEmail: localize('messages', 'EnterValidEmail')
			};

			$scope.switchOptions = {
				onLabel: '&#x2714;',
				offLabel: '&#x2716;'
			};

			$scope.load = function () {
				$scope.notifications = userSettings.getNotificationsSettings(function (notifications) {
					if (notifications.additionalEmails) {
						$scope.emails = distinct(notifications.additionalEmails.split(','));
					}
					$scope.loading = false;
				});
			};

			$scope.update = function () {
				if ($scope.loading || $scope.saving) {
					return;
				}

				$scope.saving = true;

				function success() {
					notify.success($scope.messages.success.value);
					$scope.saving = false;
				}

				function error() {
					notify.error($scope.messages.error.value);
					$scope.saving = false;
				}

				$scope.notifications.additionalEmails = distinct($scope.emails).join(',');
				userSettings.updateNotificationSettings($scope.notifications, success, error);
			};

			$scope.remove = function (index) {
				$scope.emails.splice(index, 1);
				$scope.update();
			};

			$scope.searchKeyUp = function ($event) {
				if ($event.keyCode == 13) {
					$scope.add();
				}
			};

			function validateEmail(email) {
				var emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
				return emailRegex.test(email);
			};

			$scope.add = function () {
				var name = $scope.additional;

				if (!name) {
					notify.error($scope.messages.invalidEmail.value);
					return;
				}


				if (validateEmail(name) == false) {
					notify.error($scope.messages.invalidEmail.value);
					return;
				}

				name = name.trim();
				if (name) {
					var exists = $scope.emails.filter(function (value) {
						return value.toLowerCase() === name.toLowerCase();
					}).length > 0;

					if (exists) {
						notify.error($scope.messages.existingEmail.value);
						$scope.additional = '';
						return;
					} else {
						$scope.emails.push(name);
						$scope.update();
					}
				};

				$scope.additional = '';
				$scope.update();
			}

			$scope.initialize = function () {
				$scope.load();
			}
		}
	]);
}());
(function() {
    'use strict';

    var oneKeyApp = angular.module('oneKeyApp');

    oneKeyApp.controller('toolSecurityController', [
        '$scope', '$rootScope', '$timeout', '$modal', '$log', 'localize', 'notify', 'userSettings',

        function toolSecurityController($scope, $rootScope, $timeout, $modal, $log, localize, notify, userSettings) {
            $scope.loading = true;
            $scope.saving = false;

            $scope.settings = {};

            $scope.emails = [];
            $scope.additional = '';
            $scope.notifications = {};

            $scope.guest = {};
            $scope.guestName = null;

            $scope.messages = {
                success: localize('messages', 'toolSecuritySettingsSaved'),
                error: localize('messages', 'unexpectedError'),
                invalidEmail: localize('messages', 'EnterValidEmail')

            };

            $scope.switchOptions = {
            	onLabel: '&#x2714;',
            	offLabel: '&#x2716;'
            };

            /* Notifications */

            function distinct(emails) {
                if (emails) {
                    return emails.filter(function(value, index) { return emails.indexOf(value) === index; });
                }
                return [];
            }

            $scope.updateNotifications = function() {
                if ($scope.loading || $scope.saving) {
                    return;
                }

                $scope.saving = true;

                function success() {
                    notify.success($scope.messages.success.value);
                    $scope.saving = false;
                }

                function error() {
                    notify.error($scope.messages.error.value);
                    $scope.saving = false;
                }

                $scope.notifications.additionalEmails = distinct($scope.emails).join(',');
                userSettings.updateNotificationSettings($scope.notifications, success, error);
            };

            $scope.remove = function(index) {
                $scope.emails.splice(index, 1);
                $scope.updateNotifications();
            };

            $scope.add = function() {
                var name = $scope.additional;
                if (name) {
                    name = name.trim();
                    var exists = $scope.emails.filter(function(value) { return value === name; });
                    if (exists.length == 0) {
                        $scope.emails.push(name);
                        $scope.updateNotifications();
                    }
                }
                $scope.additional = '';
            };

            /* Notifications */

            /* Tool Security */

            $scope.updateToolSecurity = function() {
                if ($scope.loading || $scope.saving) {
                    return;
                }

                updateSecuritySettings();
            };

            $scope.chainSecuritySettings = function() {
                if ($scope.loading || $scope.saving) {
                    return;
                }

                $scope.saving = true;

                if (!$scope.settings.guestsCanViewInventory) {
                    $scope.settings.guestsCanEditInventory = false;
                }

                updateSecuritySettings();
            };

            function updateSecuritySettings() {
                $scope.saving = true;

                function success() {
                    notify.success($scope.messages.success.value);
                    $scope.cachedOwnerPin = $scope.settings.ownerPin;
                    $scope.checkOwnerPin();
                    $scope.saving = false
                }

                function error() {
                    notify.error($scope.messages.error.value);
                    $scope.saving = false;
                }

                userSettings.saveToolSecuritySettings($scope.settings, success, error);
            }

            /* Tool Security */

            /* Guests */

            $scope.cachedGuestName = null;
            $scope.cachedGuestPassword = null;

            $scope.saveGuestAccount = false;

            $scope.check = function() {
                $scope.saveGuestAccount = ($scope.guest.name != $scope.cachedGuestName) ||
                    ($scope.guest.password != $scope.cachedGuestPassword);
            }

            $scope.cachedOwnerPin = null;
            $scope.saveOwnerPin = false;

            $scope.checkOwnerPin = function() {
                $scope.saveOwnerPin = ($scope.settings.ownerPin != $scope.cachedOwnerPin);
            }

            $scope.updateGuest = function() {
                if ($scope.loading || $scope.saving) {
                    return;
                }

                $scope.saving = true;

                function success(response) {
                    $scope.cachedGuestName = $scope.guest.name;
                    $scope.cachedGuestPassword = $scope.guest.password;
                    $scope.saveGuestAccount = false;

                    notify.success($scope.messages.success.value);
                    $scope.saving = false;
                    $scope.canDelete = true;
                }

                function error(response) {
                    if (response && response.data &&
                        response.data.message) {
                        // 400.
                        notify.error(response.data.message);
                    } else {
                        // 500.
                        notify.error($scope.messages.error.value);
                    }

                    $scope.saving = false;
                }

                userSettings.saveGuestAccount($scope.guest, success, error);
                
            };

            $scope.deleteGuest = function () {
                if ($scope.loading || $scope.saving) {
                    return;
                }

                $scope.saving = true;

                function success(response) {
                    $scope.cachedGuestName = $scope.guest.name;
                    $scope.cachedGuestPassword = $scope.guest.password;
                    $scope.saveGuestAccount = false;

                    notify.success($scope.messages.success.value);
                    $scope.saving = false;
                    $scope.canDelete = false;
                    $scope.cached = null;
                    $scope.cachedGuestName = null;
                    $scope.guest = {
                        name: '',
                        password: ''
                    };
                    $scope.canDelete = false;
                }

                function error(response) {
                    if (response && response.data &&
                        response.data.message) {
                        // 400.
                        notify.error(response.data.message);
                    } else {
                        // 500.
                        notify.error($scope.messages.error.value);
                    }

                    $scope.saving = false;
                }

                userSettings.deleteGuestAccount($scope.guest, success, error);

            };

            /* Guests */

            $scope.initialize = function() {
                userSettings.getFullSecuritySettings(function(response) {
                    $scope.settings = response.toolSecuritySettings;
                    $scope.notifications = response.notificationSettings;
                    $scope.guest = response.guestAccount;

                    if (!$scope.settings.guestsCanViewInventory) {
                        $scope.settings.guestsCanEditInventory = false;
                    }

                    if ($scope.guest == null) {
                        $scope.cached = null;
                        $scope.guest = {
                            name: '',
                            password: ''
                        };
                        $scope.canDelete = false;
                    }
                    else {
                        $scope.canDelete = true;
                    }

                    if ($scope.notifications.additionalEmails) {
                        $scope.emails = distinct($scope.notifications.additionalEmails.split(','));
                    }

                    $scope.cachedOwnerPin = $scope.settings.ownerPin;

                    $scope.cachedGuestName = $scope.guest.name;
                    $scope.cachedGuestPassword = $scope.guest.password;

                    $scope.loading = false;
                });
            };
        }
    ]);
}());
(function() {
    'use strict';

    var app = angular.module('oneKeyApp');

    app.service('userSettings', ['$resource', 'urls',
        function ($resource, metUrls) {
            var getNotificationsSettings = $resource(metUrls('userSettingsNotificationsApi'), {}, {
                'query': {
                    method: 'GET'
                }
            });

            var updateNotificationsSettings = $resource(metUrls('userSettingsNotificationsApi'), {}, {
                'save': {
                    method: 'PUT'
                }
            });

            var getDevices = $resource(metUrls('userSettingsDevicesApi'), {}, {
                'query': {
                    method: 'GET',
                    isArray: true
                }
            });

            var updateDevice = $resource(metUrls('updateDevice'), {}, {
                'save': {
                    method: 'PUT'
                }
            });

            var saveToolSecuritySettings = $resource(metUrls('userSettingsApi').concat('/toolsecurity'), {}, {
                'save': { method: 'POST' }
            });

            var saveGuestAccount = $resource(metUrls('accountsApi').concat('/guest'), {}, {
                'save': { method: 'POST' }
            });

            var deleteGuestAccount = $resource(metUrls('accountsApi').concat('/guest'), {}, {
                'save': { method: 'DELETE' }
            });

            var getFullSecuritySettings = $resource(metUrls('userSettingsApi').concat('/toolsecurity/full'), {}, {
                'query': { method: 'GET' }
            });

            return {
                getNotificationsSettings: function (successCallback, errorCallback) {
                    return getNotificationsSettings.query({}, successCallback, errorCallback);
                },
                updateNotificationSettings: function(settings, successCallback, errorCallback) {
                    return updateNotificationsSettings.save(settings, successCallback, errorCallback);
                },
                getDevices: function(successCallback, errorCallback) {
                    return getDevices.query({}, successCallback, errorCallback);
                },
                updateDevice: function (devices, successCallback, errorCallback) {
                    return updateDevice.save(devices, successCallback, errorCallback);
                },
                saveToolSecuritySettings: function (settings, successCallback, errorCallback) {
                    return saveToolSecuritySettings.save(settings, successCallback, errorCallback);
                },
                saveGuestAccount: function (account, successCallback, errorCallback) {
                    return saveGuestAccount.save(account, successCallback, errorCallback);
                },
                deleteGuestAccount: function (account, successCallback, errorCallback) {
                    return deleteGuestAccount.save(account, successCallback, errorCallback);
                },
                getFullSecuritySettings: function (successCallback, errorCallback) {
                    return getFullSecuritySettings.query({}, successCallback, errorCallback);
                }
            };
        }
    ]);
}());
