(function () {
  'use strict';

  angular
    .module('finally', [])

    .directive('finally', function (
      $parse
    ) {
      return {
        restrict: 'A',
        priority: 1,
        terminal: true,
        link(scope, element, attr) {
          const clickHandler = angular.isFunction(attr.ngClick) ?
            attr.ngClick :
            $parse(attr.ngClick);

          element.on('click', $event => {
            scope.$apply(() => {
              const promise = clickHandler(scope, {$event});
              if (promise && 'finally' in promise) {
                promise.finally(() => {
                  scope.$eval(attr.finally);
                });
              }
            });
          });
        },
      };
    });
})();