(function () {

    'use strict';

    angular.module('uniflash').directive('ufSettingsUpdate', ufSettingsUpdate);

    function ufSettingsUpdate() {
        var directive = {
            restrict: 'E',
            controller: SettingsUpdate,
            controllerAs: 'vm',
            templateUrl: 'nav/nw/settings_update.html',
            scope: {},
        };
        return directive;
    }

	SettingsUpdate.$inject = ['$scope', 'ticUpdateSrv', 'ticAlerts'];
	
    function SettingsUpdate ($scope,ticUpdateSrv,ticAlerts) {
		var vm = this;
		vm.updateAvailable = false;
		vm.updateErrorMsg = '';
		vm.checkingForUpdate = false;
		vm.updateChecked = false;
		vm.ticUpdateSrv = ticUpdateSrv;
		
		vm.checkUpdate = function() {
            if (ticUpdateSrv.supported()) {
				vm.checkingForUpdate = true;
				vm.updateChecked = true;
                ticUpdateSrv.available((value) => {
					vm.checkingForUpdate = false;
					vm.updateAvailable = (value === 0);
					if ( value === -1 ) {
						vm.updateErrorMsg = 'Error: Cannot start the update process.';
					} else if ( value === 1 ) {
						vm.updateErrorMsg = 'No Updates Available';
					} else if ( value === 2 ) {
						vm.updateErrorMsg = 'Error connecting to update server. Please check your proxy settings.';
					}
					
					if (!$scope.$$phase) {
                        $scope.$digest();
                    }
                });
            }
        };
		
		vm.installUpdates = function() {
            ticAlerts.showConfirm('Install Update', 'Shutting down application and install available updates. Do you wish to continue?')
                .then(() => {
                    ticUpdateSrv.install();
                });
        }
    }
})();