(function () {
    global.dashModule
        .directive('dialog', ['$timeout', '$', 'utilsService', dialogDirective]);

    function dialogDirective($timeout, $, utilsService) {
        return {
            restrict: 'A',
            scope: {
                buttonsNames: '=',
                onConfirmation: '=',
                onCancel: '=',
                onClose: '=',
                parameters: '=',
                hasButtons: '=',
                isModal: '='
            },
            link: function ($scope, $element) {
                utilsService.registerFunction('setButtonEnabled', setButtonEnabled);
                $timeout(function () {
                    let buttons = {};
                    if ($scope.hasButtons) {
                        const confirmationBtn = $scope.buttonsNames ? $scope.buttonsNames.confirmation : 'Yes';
                        const cancelBtn = $scope.buttonsNames ? $scope.buttonsNames.cancel : 'Cancel';
                        buttons[confirmationBtn] = {
                            id: 'yes-confirmation-btn',
                            text: confirmationBtn,
                            click: function () {
                                $scope.onConfirmation($scope.parameters);
                                $(this).dialog('close');
                            }
                        };
                        buttons[cancelBtn] = {
                            id: 'cancel-btn',
                            text: cancelBtn,
                            click: function () {
                                $(this).dialog('close');
                            }
                        };
                    }

                    $($element).dialog({
                        resizable: false,
                        height: 'auto',
                        width: '35%',
                        position: {
                            my: 'top',
                            at: 'top',
                            of: window
                        },
                        modal: $scope.isModal,
                        close: function () {
                            if (typeof $scope.onClose !== 'undefined') {
                                $scope.onClose($scope.parameters);
                            }
                        },
                        buttons
                    });
                });

                function setButtonEnabled(isConfirmationButtonEnabled) {
                    if (isConfirmationButtonEnabled) {
                        $('#yes-confirmation-btn').removeClass('confirmation-button-disabled');
                        $('#yes-confirmation-btn').attr('disabled', false);
                    } else {
                        $('#yes-confirmation-btn').addClass('confirmation-button-disabled');
                        $('#yes-confirmation-btn').attr('disabled', true);
                    }
                }

            }
        };
    }
})();
