window.PriceListAdmin=function (options,ProfitCenterItem) {
    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        active: false,
        containerCssSelector:".priceListForm",
        testFileMod:false,
        URL:{
            create:'',
            store:'',
            getDataTableContent:'',
            destroy:'',
        }
    };
    let PriceList = {};
    let root = this;
    let dataTableCSSSelector=null;



    /*
     * Constructor
     */
    this.construct = function (options) {
        debug('PriceListAdmin constructor called');
        $.extend(Opts, options);
    };

    let errorRowPointer=null;
    let errorRowCount=0;

    this.initErrorNavigationButton=function (){

        errorRowCount=$('.statusError').length;
        errorRowPointer=null;
        $('.priceListForm .buttonPrevError .buttonNextError').off('click')
        $('.priceListForm .buttonPrevError').on('click',function (){
            if(errorRowPointer==null){
                errorRowPointer=0;
            }else{
                if(errorRowPointer>0){
                    errorRowPointer--;
                }else{return;}
            }
            $('.statusError').removeClass('highlightedErrorRow');
            $('.priceListTableWrapper').scrollTop($($('.statusError')[errorRowPointer]).position().top);
            $($('.statusError')[errorRowPointer]).addClass('highlightedErrorRow');
        });
        $('.priceListForm .buttonNextError').off('click');
        $('.priceListForm .buttonNextError').on('click',function (){
            if(errorRowPointer==null){
                errorRowPointer=0;
            }else{
                if(errorRowPointer<errorRowCount-1){
                    errorRowPointer++;
                }else{return;}
            }
            $('.statusError').removeClass('highlightedErrorRow');
            $('.priceListTableWrapper').scrollTop($($('.statusError')[errorRowPointer]).position().top);
            $($('.statusError')[errorRowPointer]).addClass('highlightedErrorRow');
        });

    }

    this.selectedUploadFileToggle=function (fileInput){
        /*
        console.log(fileInput.attr('name'));
        console.log(fileInput[0].files[0]);
        console.log(fileInput[0].files[0].name);
        */
        if(fileInput){
            $('.containerFileUpload').addClass('d-none');
            if(fileInput[0].files[0]){
                $('.containerUploadedFileName').text(fileInput[0].files[0].name);

            }
            $('.containerFileUploadStarted').removeClass('d-none');
            $('.containerUploadedSpinner').removeClass('d-none');
        }else{
            $('.containerUploadedFileName').text('');
            $('.containerFileUploadStarted').addClass('d-none');
            $('.uploadStatusRow').addClass('d-none');

            $('.priceListTable > tbody').empty();
            $('.containerFileUpload').removeClass('d-none');
        }
    }

    this.clickNewPriceListCallBack=function () {
        root.initViewDetails();
    }
    this.clickNewPriceList=function(){
        APP.loadMainContent(Opts.URL.create,root.clickNewPriceListCallBack);
    }
    this.datatableRowActionButtonClick=function(event){
        let node=$(event[0].currentTarget);
        let row=$(dataTableCSSSelector).DataTable().row(node.parents('tr'));
        let rowData=row.data();
        //_token
        let ajaxData={};
        let ajaxUrl=Opts.URL.destroy.replace('%id%',rowData.id);
        ajaxData._token=$('input[name=_token]').val();
        $.ajax({
            url:ajaxUrl,
            data:ajaxData,
            method:"DELETE",
            success:function (data){
                if(data.success==true){
                    row.remove().draw();
                }
            }
    });
/*
*/


    }

    this.initViewList = function (options) {
        debug('listview inicialization');
        dataTableCSSSelector=Opts.containerCssSelector+' .dataTable'; //

        let colNum=$(dataTableCSSSelector+' thead th').length; //buttons insert position need
        APP.setOpts({
            datatableActionButtonClickCallBack:root.clickNewPriceList,
            datatableRowActionButtonClickCallBack:root.datatableRowActionButtonClick,

        })


        APP.dataTablePriceList=$(dataTableCSSSelector).DataTable( {
            language: {
                url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
            },

            //"ajax": "{{asset('exapmle2.json')}}",
            "ajax": Opts.URL.getDataTableContent,
            "columnDefs": [
                {
                    "targets": colNum-1,
                    "render": function ( data, type, row ) {
                        let buttons=APP.datatableAddRowTrashButton(0,arguments);
                        //buttons+=APP.datatableAddRowEditButton(0,arguments);
                        return buttons;
                    },
                },
                //{ "visible": false,  "targets": [ 0 ] }
            ],
            buttons:{

                buttons: [
                    //'createState', 'savedStates',
                    'excel','pdf',
                    {
                        extend: 'print',
                        //text: 'Print current page',
                        'title': 'title custom text',
                        'messageTop': 'Message On Top',
                        autoPrint: true
                    },
                    /**/

                    {
                        text: 'Új felvitele',
                        className: 'btn btn-success newItem',
                        attr:{
                            /*
                                                        data:{
                                                            a:1,
                                                            b:2

                                                        }
                            */
                            'data':'newItem'
                        },
                        init: function(api, node, config) {
                            $(node).removeClass('ui-button')
                        },
                        action: function ( e, dt, node, config ) {
                            APP.datatableActionButtonClickCallBack(arguments);
                            /* console.log(e);
                             console.log(dt);
                             console.log(node);
                             console.log(config);*/

                        }
                    }
                ]
            },
            "columns": [
                { "data": "id" },
                { "data": "supplierName" },
                { "data": "available" },
                { "data": "created_at" },
                { "data": "note" },
                null,
            ],
            "stateSave": true,
            "drawCallback": function( settings ) {
                APP.datatableAddRowAction(dataTableCSSSelector);
            }
        } );


    }

    this.initViewDetails = function (options) {
        $(Opts.containerCssSelector+' .datePickerClick').off('click');
        $(Opts.containerCssSelector+' .datePickerClick').on('click',function(){
            $(Opts.containerCssSelector+' .datePicker').datepicker('show');
        });

        $(Opts.containerCssSelector+' .datePicker').datepicker({
            dateFormat: 'yy-mm-dd',
            onSelect:function (dateText){
                console.log(dateText);
                $('.selectedDateText').text(dateText.replaceAll('-','.'));

                $('input[name="availableDate"]').val(dateText);

            },

        });

        $(Opts.containerCssSelector+' .buttonNewUpload').off('click');
        $(Opts.containerCssSelector+' .buttonNewUpload').on('click',function (){
            root.selectedUploadFileToggle();
        });
        $(Opts.containerCssSelector+' .buttonUpload').off('click');
        $(Opts.containerCssSelector+' .buttonUpload').on('click',function (){
            console.log('------------------');
            root.selectedUploadFileToggle();

            let data= new FormData($('.priceListForm')[0]);
            if($('.supplierSelect').val().length<1){
                Toast.create("Hiba!", 'Adjon meg beszállítót!', TOAST_STATUS.DANGER, 10000);
                return;
            }
            let fileInput=$('#inputGroupPriceListFile');
            console.log(fileInput[0].files.length<1);

            /* teszteles miatt kikapcsolva a fajl ellenorzes
            */
            if(!Opts.testFileMod){
                console.log(fileInput[0].files.length<1);
                if(fileInput[0].files.length<1){
                    Toast.create("Hiba!", 'Vállaszon ki fájlt!', TOAST_STATUS.DANGER, 10000);
                    return;
                }
            }

            data.append(fileInput.attr('name'),fileInput[0].files[0]);
            root.selectedUploadFileToggle(fileInput);

            $.ajax({
                url:Opts.URL.store,
                data:data,
                type:'POST',
                contentType:false,
                processData: false,
                beforeSend: function() {

                },
                success: function(data) {
                    console.log(data);
                    if(data.success==true){
                        root.processCheckedPriceListResponse(data);
                    }
                },
                error: function(data) {
                    console.log(data.responseJSON);
                    root.selectedUploadFileToggle();
                    ajaxErrorFieldHandler(data.responseJSON.error);
                }
            })
        });

        $(Opts.containerCssSelector+' .buttonFinalization').on('click',function (){
            let data= new FormData($('.priceListForm')[0]);
            let fileInput=$('#inputGroupPriceListFile');
            data.append(fileInput.attr('name'),fileInput[0].files[0]);
            data.append('finalization',1);
            $.ajax({
                url:Opts.URL.store,
                data:data,
                type:'POST',
                contentType:false,
                processData: false,
                beforeSend: function() {

                },
                success: function(data) {
                    console.log(data);
                    if(data.success){
                        $('.priceListTable tbody tr').remove();
                        $('.uploadStatusRow >.canFinish').hide();
                        $('.uploadStatusRow').addClass('d-none');
                        $('.priceListTable tbody').append('<tr><td colspan="99" style="text-align: center;' +
                            '    font-size: 2em;"> Árlistát elmentettük.</td></tr>');
                    }
                    /*
                    if(data.success==1){
                        root.processCheckedPriceListResponse(data);
                    }
                     */
                },
                error: function(data) {
                    console.log(data.responseJSON);
                    ajaxErrorFieldHandler(data.responseJSON.error);
                }
            })
        });

    }

    this.init = function (options) {
        console.log('PriceListAdmin init called');
        $.extend(Opts, options);
        console.log('Opt extended');
        console.log(Opts);
        /*
        Init list view
        */
        console.log('call list view Init');
        root.initViewList(options);


    }
    this.getOpts=function (){
        return Opts;
    }
    let priceListHasError=false;

    this.processCheckedPriceListResponse=function (responseData){
        priceListHasError=false;
        root.processCheckedPriceListResponseRows(responseData.rows);
        if(priceListHasError){
            $('.uploadStatusRow >.canFinish').hide();
            $('.uploadStatusRow >.canFinishError').show();
            root.initErrorNavigationButton();
        }else{
            $('.uploadStatusRow >.canFinish').show();
            $('.uploadStatusRow >.canFinishError').hide();
        }
        $('.uploadStatusRow').removeClass('d-none');
        $('.containerUploadedSpinner').addClass('d-none');
    }

    this.processCheckedPriceListResponseRows=function (responseRowsData){
        console.log('processingRows');
        for (let key in responseRowsData) {
            let rowData=responseRowsData[key];
            let templateData=rowData.originalData;
            templateData.rowNum=rowData.rowNum;
            let template=$('template[data-name="priceListTableRow"]').html()
            let render=Mustache.render(template,templateData);
            $('.priceListTable tbody').append(render);
            $('tr[data-rownum='+rowData.rowNum+']').addClass('status'+$.ucFirst(rowData.status));
            root.processResponseRowErrors(rowData.error,rowData.rowNum);
            if(rowData.changed){
                root.processResponseRowChanged(rowData.changed,rowData.rowNum);
            }
        }
    }
    this.processResponseRowChanged=function (changedArray,rowNum){
        if(changedArray.length<1){
            return;
        }
        console.log(changedArray);
        //fields error resz
        let trNode=$('tr[data-rownum='+rowNum+']');
        for (let key in changedArray) {
            let tdNode=trNode.find('td[data-pointer="'+key+'"]');
            tdNode.addClass('bg-primary');
            let changedTxtNode=$(document.createElement("span")).text(changedArray[key].old).addClass('fieldChanged');
            tdNode.append(changedTxtNode);
        }

    }
    this.processResponseRowErrors=function (errorArray,rowNum){
        if(errorArray.length<1){
            return;
        }
        //general error resz
        console.log(errorArray);
        priceListHasError = true;

        //fields error resz
        if(typeof errorArray.fields =='undefined'){
            return;
        }
        let trNode=$('tr[data-rownum='+rowNum+']');
        for (let key in errorArray.fields) {
            let tdNode=trNode.find('td[data-pointer="'+key+'"]');
            tdNode.addClass('bg-danger');
            let errorTxtNode=$(document.createElement("span")).text(errorArray.fields[key]).addClass('fieldError');
            tdNode.append(errorTxtNode);
        }
    }
};
