(function () {

    'use strict';

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

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

	ResyncDatabase.$inject = ['$scope','ticAgentAPI'];
	
    function ResyncDatabase($scope,ticAgentAPI) {
		var vm = this;
		vm.ticAgentAPI = ticAgentAPI;
        vm.step = '';
        vm.percent = 0;
		vm.error = false;
        vm.resync = function() {
			vm.step = 'Starting sync operation...';
			vm.percent = 0;
			vm.error = false;
			
			let path = require('path');
			let resyncDB = require(path.resolve('../ticloudagent/server/resync_deskdb/resync_db.js'));
			let rootFolder = path.resolve('../deskdb/content');
			
			resyncDB( rootFolder, function(step, percent) {
				vm.step = step;
				vm.percent = percent;
				console.log('per: '+percent+' step: '+step);
				$scope.$apply();
			}).then( function() {
				vm.step = 'Done! Restart application to finish.';
				vm.percent = 100;
				$scope.$apply();
			}).catch( function(e) {
				vm.step = e.message;
				vm.percent = 0;
				vm.error = true;
				$scope.$apply();
			});
        };
		
		vm.getStep = function() {
			return vm.step;
		};
		
		vm.getDownloadPercentStyle = function() {
			return {
                'width' : vm.percent.toString() + '%'
            };
		};
		
		vm.close = function() {
			return ticAgentAPI.closeAgent();
		};
    }
})();