(function () {

    'use strict';

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

    function ufUpdateChecker() {

        let directive = {
            restrict: 'E',
            controller: UpdateChecker,
            controllerAs: 'vm',
            templateUrl: 'ti_common/nw/update_checker.template.html',
            scope: {},
        };
        return directive;
    }


    class UpdateChecker {
        static $inject = ['$scope', 'ticAlerts', 'ticUpdateSrv'];
        private updatesSupported;
        private checkingForUpdates;
        private updatesFound;

        constructor(private $scope, private ticAlerts, private ticUpdateSrv) {
            this.updatesSupported = this.ticUpdateSrv.supported();
            this.checkUpdate();
        }

        checkUpdate() {
            if (this.ticUpdateSrv.checkUpdateOnStartup && this.updatesSupported) {
                this.checkingForUpdates = true;
                this.ticUpdateSrv.available((value) => {
                    this.checkingForUpdates = false;
                    this.updatesFound = (value===0);
                    if (!this.$scope.$$phase) {
                        this.$scope.$digest();
                    }
                });
            }
        }

        installUpdates() {
            this.ticAlerts.showConfirm('Install Update', 'Shutting down application and install available updates. Do you wish to continue?')
                .then(() => {
                    this.ticUpdateSrv.install();
                });
        }

    }

})();