var Workflow = (function() {


    return {
        init: function(parent) {



            if(!parent) {
                parent = $('body');
            }

            var $stateSelects = $('[data-select-action]', parent);

            if($stateSelects.data('initialized')) {

                return;
            }

            var _get = function(d, params) {

                var target = $(params.initialEvent.currentTarget);

                var stack = target.data('selectionStack');
                var destinationStateOption = stack[stack.length - 1];

                var originStateOption = stack[stack.length - 2];
                if(originStateOption.get(0) == destinationStateOption.get(0)) {
                    params.managed = true;

                    var _error = new Error();
                    _error.launch = false;
                    d.reject(_error);
                    return;
                }


                if(true == target.data('isCalling')) {

                    params.managed = true;
                    var _error = new Error();
                    _error.launch = false;
                    d.reject(_error);
                    return;
                }

                target.data('isCalling', true);
                var id = target.data('id-content');

                var postParameters = $.extend({
                    ids: id,
                    allSelected: contentSelected.allSelected
                }, postParams(contentSelected.formsCollection));

                params.message = Translator.transChoice(
                    params.message,
                    1, {
                        'state': destinationStateOption.val(),
                        'originState': originStateOption.val()
                    }
                );

                params.url = destinationStateOption.data('url') + '&' + $.param(postParameters);

                target.prop('disabled', true);




            };

            var _success = function(params) {
                params.managed = true;

                if (typeof params.response !== "undefined") {
                    showToastrNotification(params.response.type, Translator.trans(params.response.message));
                } else {
                    showToastrNotification('success', Translator.trans('workflow.messages.reachable.success'));
                }
                //window.location.reload();
            };

            var _always = function() {
                this.prop('disabled', false);
                this.data('isCalling', false);
                //window.location.reload();
            };

            var _error = function(error) {

                if(error.hasOwnProperty('launch') && error.launch == false) {
                    return;
                }

                this.prop('disabled', false);
                var target = this;
                var stack = target.data('selectionStack');
                stack.pop();
                var last = stack[stack.length - 1];

                target.data('selectionStack', stack);
                $('option', target).each(function(i,e) {
                    var option = $(e);
                    if(option.is(last)) {

                        option.prop('selected', true);
                        target.trigger('change');
                        return;
                    }
                });
            };

            if(!Pagination.onChange.has(Workflow.onChange)) {
                Pagination.onChange.add(Workflow.onChange);
            }

            $stateSelects.each(function(i,e) {

                var _this = $(e);

                _this.data('selectionStack', [$('option:selected', _this)]);
                _this
                    .on('change', function() {
                        var lastSelected = _this.data("last-selected");
                        var selectionStack = _this.data('selectionStack');
                        var last = lastSelected||selectionStack[selectionStack.length - 1];
                        var current = $('option:selected', _this);

                        selectionStack.push(current);

                        _this.data('selectionStack', selectionStack);
                        _this.attr('data-style', current.attr('class'));

                        _this.data("last-selected", current);

                        _this
                            .data('selectpicker')
                            .$newElement
                            .find('button.selectpicker')
                            .removeClass(last.attr('class'))
                            .addClass(current.attr('class'))
                        ;
                    });

                var $action = new ModifyContentActivity();

                $action
                    .setSelector(_this)
                    .setEvent('change')
                    .setHandler('onError', function(error) {
                        if(error.hasOwnProperty('launch') && error.launch == false) {

                            return;
                        }

                        this.signals._error.dispatch(error);

                        var title   = error.hasOwnProperty('title') ? error.title :  Translator.trans("cs_core.messages.deleting_error");
                        var message = error.message;

                        window.bootstrap.modal.show(title, message, Translator.trans("cs_core.action.accept"), true);

                    })
                    .on('_get', _get)
                    .on('_success', _success.bind(_this))
                    .on('_error', _error.bind(_this))
                    .on('_always', _always.bind(_this))
                    .init()
                ;
            }).data('initialitzed', true);


        },
        onChange: function(container) {
            $('.bs-select', container).selectpicker();
            Workflow.init();
        },
    };

})();

$(function() {
    Workflow.init();
});
