/**
 * KeychainModalCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('KeychainModalCtrl', ['$scope', 'Customer', '$http', 'apiUrl', '$q', 'ErrorsHandler', '$uibModalInstance', 'Device', 'Keychain', 'TaskId', 'PasswordsService', 'Tasks', 'Messenger', function ($scope, Customer, $http, apiUrl, $q, ErrorsHandler, $uibModalInstance, Device, Keychain, TaskId, PasswordsService, Tasks, Messenger) {

	$scope.new = { type: 'windows', device_id: null, username: '', password: '' };

	$scope.loadPasswords = function () {
		Keychain.get({ client_id: Customer.id, client_type: Customer.type }, function (response) {
			$scope.keychain = response.data;
		});
	};

	$scope.load = function () {

		$scope.loadPasswords();

		Device.get({ client_type: Customer.type, client_id: Customer.id }, function (response) {
			$scope.client_devices = response.data;
		});

	};

	$scope.load();

	$scope.createPassword = function () {

		if (!$scope.isValidForm())
			return;
		$scope.new.client_id = Customer.id;
		$scope.new.client_type = Customer.type;

		// Convert empty string to null for device_id
		if ($scope.new.device_id === '' || $scope.new.device_id === 'null') {
			$scope.new.device_id = null;
		}

		console.log('Creating password with data:', $scope.new);

		Keychain.save($scope.new, function (response) {
			console.log('Password creation response:', response);
			// Reload the passwords list to ensure proper data structure
			$scope.loadPasswords();
			$scope.new = { type: 'windows', device_id: null, username: '', password: '' };
		});
	};

	$scope.update = function (password, field, value) {
		var data = {},
			deferred = $q.defer();
		data[field] = value;

		$http.post(apiUrl('keychain/' + password.id), data)
			.success(function (response) {
				deferred.resolve();
				angular.extend(password, response || {});
			})
			.error(function (a, b) {
				ErrorsHandler(a, b);
				deferred.resolve('Something went wrong');
			});

		return deferred.promise;
	};

	$scope.isValidForm = function () {
		if (!$scope.new.username)
			return false;
		if (!$scope.new.password)
			return false;

		return true;
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

	$scope.getDeviceName = function (id) {

		var name = 'General';

		if (id != null && id > 0) {

			_.each($scope.client_devices, function (device) {
				if (device.id == id) {
					// Handle the correct nested structure: device.model_number.manufacturer.name
					if (device.model_number && device.model_number.manufacturer && device.model_number.manufacturer.name && device.model_number.model_number) {
						name = device.model_number.manufacturer.name + " " + device.model_number.model_number;
					} 
					// Fallback if only model number exists
					else if (device.model_number && device.model_number.model_number) {
						name = device.model_number.model_number;
					}
					// Last resort
					else {
						name = device.type || ('Device ' + id);
					}
				}
			});

		}

		return name;

	};

	//Add the password to the task
	$scope.addPasswordToTask = function (password) {

		Tasks.addKeychain({ id: TaskId, keychain_id: password.id }, function () {
			Messenger("The password has been added to the task!");
			Keychain.get({ task_id: TaskId }, function (response) {
				PasswordsService.setPasswords(response.data);
			});
		}, ErrorsHandler);
	};

	//Disable the password. So it wont be visible any more
	$scope.disablePassword = function (password) {
		Keychain.delete({ keychainId: password.id, disabled: true }, function () {
			$scope.loadPasswords();
			Keychain.get({ task_id: TaskId }, function (response) {
				PasswordsService.setPasswords(response.data);
			});
		});
	};

	// Copy password to clipboard
	$scope.copyToClipboard = function (text) {
		if (!text) return;

		// Create a temporary textarea element
		var textarea = document.createElement('textarea');
		textarea.value = text;
		textarea.style.position = 'fixed';
		textarea.style.opacity = '0';
		document.body.appendChild(textarea);
		textarea.select();

		try {
			document.execCommand('copy');
			Messenger("Password copied to clipboard!");
		} catch (err) {
			Messenger("Failed to copy password", "error");
		}

		document.body.removeChild(textarea);
	};




}]);
