//<!--todo сделать оповещение что префиксы не настроены -->
$(document).ready(function () {
    var lines,
        LinesTab = {
            ajax: {
                url: "ajax.php",
                type: "POST",
                data: {
                    command: 'updateLine',
                    module: window.modulename,
                },
            },
            fields: {
                lineID: '#lineID',
                did: '#did',
                number: '#number',
                prefix: '#prefix',
            },
            buttons: {
                modal_addLine_ok: '#modal_addLine_ok',
                edit: '.iu_lines_edit',
                remove: '.iu_lines_delete'
            },
            modal: '#addLine',
            title: '#addLine .panel-title',
            LinesModal:{
                self: '#Lines',
                dialog: '#Lines > div.modal-dialog',
                table: '#Lines_panel_table_modal'
            },
            LinesPanel: {
                self: '#LinesPanel',
                body: '#LinesPanel > div.panel-body',
                table: '#Lines_panel_table'
            },

            init: function () {
                lines = this;
                this.bindUIActions();
            },

            /**
             * обработчики кнопок
             */
            bindUIActions: function () {
                $(lines.modal).on('show.bs.modal', function (event) {
                    $(lines.title).html(' ' + $('#modal_action_line').attr('value'));
                    if(event.relatedTarget.dataset.id) {
                        $(lines.fields.prefix).attr('data-base-val',event.relatedTarget.dataset.prefix);
                        $(lines.title).prepend($('#modal_action_edit').attr('value'));
                        $(lines.fields.lineID).attr('data-id',event.relatedTarget.dataset.id);
                        $(lines.fields.number).val(event.relatedTarget.dataset.lineNumber);
                        $(lines.fields.prefix).val(event.relatedTarget.dataset.prefix);
                        $(lines.buttons.edit +'[data-line-number="'+event.relatedTarget.dataset.lineNumber +'"]' ).each(function(i,element) {
                            if($(element).attr('data-id') != event.relatedTarget.dataset.id && $(element).attr('data-prefix').length >0) {
                                lines.disablePrefixField(element);
                            }
                        });
                        $(lines.fields.did).val(event.relatedTarget.dataset.lineDid);
                    }else{
                        $(lines.title).prepend($('#modal_action_add').attr('value'));

                    }
                });
                $(lines.buttons.modal_addLine_ok).on('click', function (event) {
                    if (lines.__checkInvalid()) {
                        if($(lines.buttons.edit + '[data-line-number="' + $(lines.fields.number).val() + '"]').length > 1) {
                            if(confirm($('#number_exists').attr('value'))){
                                lines.update(event);
                            }
                        }else{
                            lines.update(event);
                        }
                    }
                });
                $(lines.modal).on('hidden.bs.modal',function () {
                    lines.__clearModal();
                });
                $(lines.fields.number).on('change',function (event) {
                    let checkState = lines.checkField(event);
                    if(checkState){
                        lines.disablePrefixField(checkState);
                    }else{
                        lines.enablePrefixField();
                    }

                });
            },
            checkField: function(event){
                let $return;
                if($(lines.buttons.edit + '[data-line-number="' + event.target.value + '"]').length > 0) {
                    $(lines.buttons.edit + '[data-line-number="' + event.target.value + '"]').each(function (i, element) {
                        if ($(element).attr('data-id') != $(event.target).parent().parent().parent().parent().parent().parent().parent().children('#lineID').attr('data-id')){
                            if($(element).attr('data-prefix').length > 0){
                                $return  = element;
                                return false;
                            }
                        }
                    });

                }
                return $return;
            },
            enablePrefixField: function(){
                $(lines.fields.prefix + ':disabled').attr('placeholder','');
                $(lines.fields.prefix + ':disabled').attr('disabled',false);
                if($(lines.fields.prefix).attr('data-base-val')){
                    $(lines.fields.prefix).val($(lines.fields.prefix).attr('data-base-val'));
                }
            },
            disablePrefixField: function(element){
                $(lines.fields.prefix).attr('data-base-val',$(lines.fields.prefix).val());
                $(lines.fields.prefix).attr('disabled', true);
                $(lines.fields.prefix).attr('placeholder', $(element).attr('data-prefix'));
                $(lines.fields.prefix).val('');
},

            /**
             * обновление линии
             */
            update: function (event) {
                if($(lines.fields.lineID).attr('data-id'))
                lines.ajax.data['id'] = $(lines.fields.lineID).attr('data-id');
                lines.ajax.data['did'] = ($(lines.fields.did).val()) ? $(lines.fields.did).val() : '';
                lines.ajax.data['number'] = ($(lines.fields.number).val()) ? $(lines.fields.number).val() : '';
                lines.ajax.data['prefix'] = ($(lines.fields.prefix).val()) ? $(lines.fields.prefix).val() : '';
                $.ajax({
                    url: lines.ajax.url,
                    type: lines.ajax.type,
                    data: lines.ajax.data,
                    success: function (data) {
                        fpbxToast('Complete', 'Update line', 'success');
                        IDTable.Lines_panel_table = data[0];
                        IDTable.CallbacksTable = data[1];
                    }}).then(function () {

                    lines.linesTableUpdate();
                });
                $(event.currentTarget).parent().parent().parent().parent().modal('hide');
                toggle_reload_button("show");
            },
            linesTableUpdate: function(){
                if ($(lines.LinesModal.self).css('display') === 'block'){
                    $(lines.LinesModal.table).bootstrapTable('refresh');
                }
                $(lines.LinesPanel.table).bootstrapTable('refresh');
                $('#CallbacksTable').bootstrapTable('refresh');
            },
            __clearModal: function(){
                $(lines.fields.lineID).attr('data-id','');
                $(lines.fields.number).val('');
                $(lines.fields.did).val('');
                $(lines.fields.prefix).val('');
                $(lines.fields.prefix + ':disabled').attr('placeholder','');
                $(lines.fields.prefix + ':disabled').attr('disabled',false);
            },
            __checkInvalid: function () {
                if (!$(lines.fields.did).val()) {
                    warnInvalid($(lines.fields.did));
                    return false;
                }
                if (!$(lines.fields.number).val()) {
                    warnInvalid($(lines.fields.number));
                    return false;
                }
                if ($(lines.fields.prefix).val().length && (!/^\d+$/.test($(lines.fields.prefix).val()))) {
                    warnInvalid($(lines.fields.prefix));
                    return false;
                }
                return true;
            },
        };

    LinesTab.init();
});