(function () {
    'use strict';

    angular
        .module('editorRotas')
        .directive('clockPicker', clockPicker);

    clockPicker.$inject = [];

    /* @ngInject */
    function clockPicker() {
        var directive = {
            restrict: 'A',
            require: 'ngModel',
            replace: false,
            link: link,
            scope: false
        };

        function link(scope, element, attr, ngModel) {
            var input = element.find('input');
            var icons = element.find('i');

            scope.vm.dateOptions = {};

            element.clockpicker({
                donetext: 'Selecionar',
                minTime: attr.minTime,
                maxTime: attr.maxTime,
                afterDone: function () {
                    if (attr.callback) {
                        scope.vm[attr.callback](this);
                        scope.$apply();
                    }
                },
                afterHide: function () {
                    ngModel.$setViewValue(element.val());
                    ngModel.$setTouched();

                    ngModel.$viewChangeListeners.forEach(function (func) {
                        func()
                    });

                    scope.$apply();
                }
            });

            icons.on('click', function () {
                if (input.is(':focus')) {
                    input.trigger('blur');
                } else {
                    input.trigger('focus');
                }
            });
        }

        return directive;
    }
})();
