(function (angular) {
    angular.module('todoList').directive('exlordMessages', ExlordMessages);

    ExlordMessages.$inject = [];

    function ExlordMessages() {
        return {
            restrict: 'E',
            template: '<div class="messages">' +
                      '     <div ng-repeat="m in ctrl.messages" class="alert alert-{{m.type}}">' +
                      '         <button type="button" class="close" aria-label="Close" ng-click="ctrl.close($index)">' +
                      '             <span aria-hidden="true">&times;</span>' +
                      '         </button>' +
                      '         <strong ng-bind="m.title"></strong>' +
                      '         <span ng-bind="m.text"></span>' +
                      '     </div>' +
                      '</div>',
            scope: {
                api: '=?'
            },
            controller: ExlordMessageController,
            controllerAs: 'ctrl'
        }
    }

    ExlordMessageController.$inject = ['$scope', '$timeout'];

    function ExlordMessageController($scope, $timeout) {
        var vm = this;
        vm.messages = [];
        vm.close = closeMessage;

        $scope.api = $scope.api || {};
        $scope.api.add = addMessage;

        function addMessage(type, title, text) {
            vm.messages.push({type: type, title: title, text: text});
            var index = vm.messages.length - 1;
            $timeout(function () {
                closeMessage(index);
            }, 2000);
        }

        function closeMessage(index) {
            if (vm.messages.length && vm.messages.length > index) {
                vm.messages.splice(index, 1);
            }
        }
    }
})
(angular);