if(typeof DataModelProfitCenter==='undefined'){
    class DataModelProfitCenter extends DataModel{

        /*
         * Constructor
         */
        constructor (data,options) {
            super(data,options)
            if(typeof this.contact ==="undefined"){
                this.contact=[];
            }
            if(typeof this.address ==="undefined"){
                this.address=[];
            }
            console.log(this.constructor.name+' constructor called');
        };
    };
    window.DataModelProfitCenter=DataModelProfitCenter;
}

window.ProfitCenterAdmin=function (options,ProfitCenterItem) {
    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        token: null,
        containerCssSelector: '.containerProfitCenter',
        testMode: false,
        URL: {
            getDataTableContent: '',
            index: '',
            show: '',
            edit: '',
            create: '',
            store: '',
            update: '',
            destroy: '',
        },
        dataTable: {
            orderDirective: [1, 'asc']
        },
        onAfterInitViewDetails: function () {
        }
    };
    let ProfitCenter = {};
    let root = this;
    let contactPopupWorkflow = 'new';
    let addressPopupWorkflow = 'new';
    let CSSSelectorForm='';
    let dataTableCSSSelector='';
    /*
     * Constructor
     */
    this.construct = function (options, ProfitCenterItem) {
        console.log('ProfitCenterAdmin constructor called');
        $.extend(Opts, options);
        if (!ProfitCenterItem) {
            console.log('ProfitCentert letre kellet hozni ');
            if (!APP.ProfitCenter) {
                APP.ProfitCenter = new window.DataModelProfitCenter();
            }
            root.ProfitCenter = APP.ProfitCenter;
        }
        CSSSelectorForm=Opts.containerCssSelector+' .profitCenterForm';
    };
    this.getOpts = function () {
        return Opts;
    }
    this.getData=function (){
        return root.ProfitCenter;
    }

    this.init=function (options,ProfitCenterItem){
        $.extend(Opts, options);

        if(Opts.testMode){
            return root.testMode();
        }
        if(ProfitCenterItem){
            root.ProfitCenter=ProfitCenterItem
        }
        root.initViewList();
    }
    this.clickNew=function () {
        debug('clickNew');
        APP.loadMainContent(Opts.URL.create,root.clickNewCallBack);
    }

    this.clickNewCallBack=function () {
        debug('callbackNew');
        root.ProfitCenter=new window.DataModelProfitCenter();
        root.initViewDetails();
    }

    this.initViewDetails=function (options,SupplierItem){
        debug('**call initViewDetails ');
        /**
         * Contact Popup setup
         */
        if(!APP.ContactPopUp){
            console.log('nincs APP.ContactPopUp')
            APP.ContactPopUp = new window.ContactPopUp();
        }else{
            console.log('mar van  APP.ContactPopUp')
        }
        APP.ContactPopUp.init({
            active:true,
            onAfterSave:root.contactAction
        });
        root.renderContact();
        $(CSSSelectorForm+' .buttonNewContact').bind('click',function (){
            APP.ProfitCenterAdmin.setContactPopupWorkflow('new');
            APP.ContactPopUp.clearData();
            APP.ContactPopUp.show();
        });
        /**
         * Address Popup setup
         */
        if(!APP.AddressPopUp){
            console.log('nincs APP.AddressPopUp')
            APP.AddressPopUp = new window.AddressPopUp();
        }else{
            console.log('mar van  APP.AddressPopUp')
        }
        APP.AddressPopUp.init({
            active:true,
            onAfterSave:root.addressAction
        });
        root.renderAddress();
        $(CSSSelectorForm+' .buttonNewAddress').bind('click',function (){
            APP.ProfitCenterAdmin.setAddressPopupWorkflow('new');
            APP.AddressPopUp.clearData();
            APP.AddressPopUp.show();
        });
        /**
         *
         */

        $('[data-toggle="tooltip"]').tooltip();
        initRadioButtons({
            onChange: function (value,node) {
                debug(value);
                debug(node);
                /*

                                    if(node==='profitCenterMultiAddress'){
                                        if(value==1){
                                            $('.containerMultiAddress').removeClass('d-none');
                                        }else{
                                            $('.containerMultiAddress').addClass('d-none');
                                        }
                                    }

                */
                if(node==='addressEqual'){
                    if(value==1){
                        $(CSSSelectorForm+' .containerMultiAddress').addClass('d-none');
                        $(CSSSelectorForm+' .containerMultiAddressSwitch').addClass('d-none');
                    }else{
                        $(CSSSelectorForm+' .containerMultiAddress').removeClass('d-none');
                        $(CSSSelectorForm+' .containerMultiAddressSwitch').removeClass('d-none');
                    }
                }

            }
        });
        $(CSSSelectorForm+" :input").inputmask({
            "onincomplete": function () {
                console.log($(this).data('required'));
                if ($(this).val().length > 0 || $(this).data('required') === true) {
                    $(this).addClass('is-invalid');
                }
            },
            "oncomplete": function () {
                $(this).removeClass('is-invalid');
                $(this).addClass('is-valid');
            },
            "oncleared": function () {
                console.log('cleared');
                $(this).removeClass('is-invalid');
            }
        });

        $(CSSSelectorForm+' button.FormSaveButton').off('click');
        $(CSSSelectorForm+' button.FormSaveButton').on('click',root.clickSaveButton);
/*
        $("input[name=logoFile]").change(function(){
            setImageFromLocal(this,Opts.containerCssSelector+' .imageLogo');
        });
*/

        //Opts.onAfterInitViewDetails();
        debug('**end initViewDetails ');
    }
    this.setDetailsViewData=function () {
        debug('setDetailsViewData');
        let CSSSelectorForm=Opts.containerCssSelector+' .profitCenterForm';
        let needToSet=[
            'name','hooreycaId','nameId',
            'email','postCode','city','street','phone','mobil'
        ];
        $.each(needToSet,function () {
            // debug(this); //alapadatok beallitasanak logolasa
            if(typeof root.ProfitCenter[this]!='undefined'){
/* //alapadatok beallitasanak logolasa
                debug(root.ProfitCenter[this]);
                debug(CSSSelectorForm+' input[name='+this+']');
                debug($(CSSSelectorForm+' input[name='+this+']'));
*/
                $(CSSSelectorForm+' input[name='+this+']').val(root.ProfitCenter[this]);
            }
        })
        if(typeof root.ProfitCenter['note']!='undefined'){
            $(CSSSelectorForm+' textarea[name=note]').val(root.ProfitCenter.note);
        }
        $(CSSSelectorForm+' *[data-toggle=canSee][data-title='+root.ProfitCenter.canSee+']').click();
        $(CSSSelectorForm+' *[data-toggle=hooreycaDataActive][data-title='+root.ProfitCenter.hooreycaDataActive+']').click();

        if(typeof root.ProfitCenter['logoFile']!='undefined' && (root.ProfitCenter['logoFile'])){
            $(CSSSelectorForm+' img.imageLogo').attr('src',root.ProfitCenter['logoFile']);
        }

        $(CSSSelectorForm+' *[data-toggle=addressEqual][data-title='+root.ProfitCenter.addressEqual+']').click();
        $(CSSSelectorForm+' *[data-toggle=multiAddress][data-title='+root.ProfitCenter.multiAddress+']').click();
        /*debug(root.ProfitCenter.address.length);
        if(root.ProfitCenter.address.length>0){
            $(CSSSelectorForm+' *[data-toggle=addressEqual][data-title=0]').click();
            if(root.ProfitCenter.address.length>1){
                $(CSSSelectorForm+' *[data-toggle=multiAddress][data-title=1]').click();
            }
        }
        */
        let supplier=[];
        $.each(root.ProfitCenter.suppliers,function () {
            supplier.push(this.name);
        });
        //$(CSSSelectorForm+' .profitCenterSelect').val(profitCenter).change();
        $.each(supplier,function () {
            $('input[value="'+$.escapeSelector(this)+'"]').prop( "checked", true );
        })

    }

    this.resetContactTable=function (){
        $(CSSSelectorForm+' .contactTable tbody tr').remove();
        root.renderContact();
    }
    this.renderContact=function (){
        let rowNum=1;
        console.log('renderingContacts');
        $.each(root.ProfitCenter.getData('contact'),function (){
            let contactData=this;
            contactData.rowNum=rowNum;
            let template=$('template[data-name="profitCenterContactTableRow"]').html()
            let render=Mustache.render(template,contactData);
            $('.contactTable tbody').append(render);
            rowNum++;
        });
        root.bindContactClickAction();
    }

    this.bindContactClickAction =function (){
        $('.contactTable .buttonDelete').unbind('click');
        $('.contactTable .buttonDelete').bind('click',root.contactDeleteClick);
        $('.contactTable .buttonEdit').unbind('click');
        $('.contactTable .buttonEdit').bind('click',root.contactEditClick);

    }
    this.contactDeleteClick=function (event){
        let row=$(this).closest('tr');
        let id=row.find('input[name=contactId]').val();
        console.log(id);
        root.ProfitCenter.contact=root.ProfitCenter.contact.filter(
            function (value,index,arr){
                if (value.id!==id*1){
                    return  true;
                }
                return false;
            }
        );
        console.log(root.ProfitCenter.contact);
        row.remove();
        root.resetContactTable();
    }
    this.getContactPopupWorkflow = function () {
        return contactPopupWorkflow;
    }
    this.setContactPopupWorkflow = function (status) {
        contactPopupWorkflow=status;
    }


    this.contactEditClick=function (event){
        console.log(this);
        let row=$(this).closest('tr');
        let id=row.find('input[name=contactId]').val();
        console.log(id);
        root.setContactPopupWorkflow('edit');
        APP.ContactPopUp.loadData(id);
    }
    this.contactAction=function (contactData){
        console.log('nah most kellene meg valamit csinalni.')
        if(root.getContactPopupWorkflow()=='new'){
            root.addContact(contactData);
        }else if(root.getContactPopupWorkflow()=='edit'){
            root.editContact(contactData.id,contactData);
        }
    }
    this.addContact=function (contactData){
        /*
        fel kell venni a sorba
         */
        root.ProfitCenter.contact.push(contactData);
        contactData.rowNum=root.ProfitCenter.contact.length;
        let template=$('template[data-name="profitCenterContactTableRow"]').html()
        let render=Mustache.render(template,contactData);
        $(CSSSelectorForm+' .contactTable tbody').append(render);
        root.bindContactClickAction();
        Toast.enableTimers(false);
        Toast.create("Kapcsolat tartó hozzáadva!", contactData.name+" nevű kapocsolattartó hozzáadva", TOAST_STATUS.SUCCESS,5000);
    }
    this.editContact=function (id,contactData){

        let newContacts=[];
        $.each(root.ProfitCenter.getData('contact'),function (index){
            if(this.id==id){
                newContacts.push(contactData);
            }else{
                newContacts.push(this);
            }
        });
        root.ProfitCenter.contact=newContacts;
        root.resetContactTable();
        Toast.create("Kapcsolat adatai módosítva!", contactData.name+" nevű kapocsolattartó módosítva", TOAST_STATUS.SUCCESS,5000);
    }


    /***************
     *
     * Address function
     *
     */
    this.resetAddressTable=function (){
        $(CSSSelectorForm+' .addressTable tbody tr').remove();
        root.renderAddress();
    }
    this.renderAddress=function (){
        let rowNum=1;
        console.log('renderingAddress');
        $.each(root.ProfitCenter.getData('address'),function (){
            let itemData=this;
            itemData.rowNum=rowNum;
            let template=$('template[data-name="profitCenterAddressTableRow"]').html()
            debug(itemData);
            let render=Mustache.render(template,itemData);
            $('.addressTable tbody').append(render);
            rowNum++;
        });
        root.bindAddressClickAction();
    }

    this.bindAddressClickAction =function (){
        $('.addressTable .buttonDelete').unbind('click');
        $('.addressTable .buttonDelete').bind('click',root.addressDeleteClick);
        $('.addressTable .buttonEdit').unbind('click');
        $('.addressTable .buttonEdit').bind('click',root.addressEditClick);

    }
    this.addressDeleteClick=function (event){
        let row=$(this).closest('tr');
        let id=row.find('input[name="addressId[]"]').val();
        console.log(id);
        root.ProfitCenter.address=root.ProfitCenter.address.filter(
            function (value,index,arr){
                if (value.id!=id) return true;
            }
        );
        console.log(root.ProfitCenter.address);
        row.remove();
        root.resetAddressTable();
    }
    this.getAddressPopupWorkflow = function () {
        return addressPopupWorkflow;
    }
    this.setAddressPopupWorkflow = function (status) {
        addressPopupWorkflow=status;
    }


    this.addressEditClick=function (event){
        console.log(this);
        let row=$(this).closest('tr');
        let id=row.find('input[name="addressId[]"]').val();
        console.log(id);
        root.setAddressPopupWorkflow('edit');
        APP.AddressPopUp.loadData(id);
    }
    this.addressAction=function (itemData){
        console.log('nah most kellene meg valamit csinalni.')
        if(root.getAddressPopupWorkflow()=='new'){
            root.addAddress(itemData);
        }else if(root.getAddressPopupWorkflow()=='edit'){
            root.editAddress(itemData.id,itemData);
        }
    }
    this.addAddress=function (ItemData){
        /*
        fel kell venni a sorba
         */
        root.ProfitCenter.address.push(ItemData);
        ItemData.rowNum=root.ProfitCenter.address.length;
        let template=$('template[data-name="profitCenterAddressTableRow"]').html()
        let render=Mustache.render(template,ItemData);
        $(CSSSelectorForm+' .addressTable tbody').append(render);
        root.bindAddressClickAction();
        Toast.enableTimers(false);
        Toast.create("Cím hozzáadva!", ItemData.street+" hozzáadva", TOAST_STATUS.SUCCESS,5000);
    }
    this.editAddress=function (id,itemData){

        let newItem=[];
        $.each(root.ProfitCenter.getData('address'),function (index){
            if(this.id==id){
                newItem.push(itemData);
            }else{
                newItem.push(this);
            }
        });
        root.ProfitCenter.address=newItem;
        root.resetAddressTable();
        Toast.create("cím adatai módosítva!", itemData.street+" módosítva", TOAST_STATUS.SUCCESS,5000);
    }

    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.clickNew,
            datatableRowActionButtonClickCallBack:root.datatableRowActionButtonClick,

        })
        let orderDirective=Opts.dataTable.orderDirective;
        if(typeof options['orderDirective']!='undefined'){
            orderDirective=options['orderDirective'];
        }
        $(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;
                    },
                },
                {
                    "targets": 1,
                    "render": function ( data, type, row ) {
                        return type === "sort" ? data.latinise() : data;
                    },
                },
                //{ "visible": false,  "targets": [ 0 ] }
            ],
            buttons:{
                buttons: [
                    '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": "name" },
                { "data": "hooreycaId" },
                { "data": "nameId" },
                { "data": "created_at" },
                null,
            ],
            "order": orderDirective,
            //"stateSave": true,
            "drawCallback": function( settings ) {
                APP.datatableAddRowAction(dataTableCSSSelector);
            }
        } );
        debug('listview end');
    }
    this.datatableRowActionButtonClick=function (event){
        debug('datatableRowActionButtonClick');
        let node=$(event[0].currentTarget);
        let row=$(dataTableCSSSelector).DataTable().row(node.parents('tr'));
        let rowData=row.data();
        let actionName='datatableRowAction'+node.data('buttontype').capitalize();
        if (typeof root[actionName] === "function") {
            return root[actionName](rowData,node)
        }
    }
    this.datatableRowActionEdit=function (rowData,node) {
        console.log('datatableRowActionEdit Called');
        //Opts.onAfterInitViewDetails=root.autofillDetails;
        let ajaxUrl=Opts.URL.edit.replace('%id%',rowData.id);
        /*
                console.log(Opts.URL);
                console.log(ajaxUrl);
        */
        APP.loadMainContent(ajaxUrl,root.initViewDetails);
        console.log('datatableRowActionEdit End');
    }
    this.datatableRowActionDelete=function (rowData,node) {
        console.log('datatableRowActionDelete Called');
        let row=$(dataTableCSSSelector).DataTable().row(node.parents('tr'));
        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.clickSaveButton=function (event) {
        debug('Save clicked');
        event.preventDefault();
        debug(CSSSelectorForm);
        debug($(CSSSelectorForm));
        if ($(CSSSelectorForm)[0].checkValidity() === false) {
            console.log('validaton false');
            event.stopPropagation();
            return;
        } else {
            console.log('validaton ok');
            //do your ajax submition here
        }
        let ajaxData=root.formDataToDataObjectAPICall(CSSSelectorForm);

        let ajaxUrl=Opts.URL.store;
        let ajaxMethod="POST";
        if(root.ProfitCenter.id){
            ajaxUrl=Opts.URL.update.replace('%id%',root.ProfitCenter.id);
            //ajaxMethod="PUT";
            //ajaxData=new FormData($(CSSSelectorForm)[0]);
            ajaxData.append('_method','PUT');
        }
/*
        debug(ajaxUrl);
        debug(ajaxMethod);
        debug(ajaxData.entries());
        for (var pair of ajaxData.entries()) {
            console.log(pair[0]+ ', ' + pair[1]);
        }
*/

        console.table(Object.fromEntries(ajaxData));

        $.ajax({
            url:ajaxUrl,
            data:ajaxData,
            type:ajaxMethod,
            contentType:false,
            processData: false,
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            },

            success:function (data){
                debug(data);
                if(data.success==true){

                    //Opts.onAfterInitViewDetails=root.autofillDetails;
                    Opts.dataTable.orderDirective=[0, 'desc'];
                    Toast.create("Sikeres rögzítés!", ajaxData.get('name')+" nevű beszálllító elmentve", TOAST_STATUS.SUCCESS,5000);
                    APP.loadMainContent(Opts.URL.index+'?init=0',root.initViewList);
                }
            }
        });
    }

    this.formDataToDataObjectAPICall = function (CSSSelectorForm) {
        let ajaxData=new FormData($(CSSSelectorForm)[0]);
/*
        $.each(ajaxData.getAll('productGroup'),function(key,value){
            ajaxData.append('productGroup[]',value);
        })
*/
        $.each(ajaxData.getAll('contactId'),function(key,value){
            ajaxData.append('contactId[]',value);
        })

        ajaxData.append('_token',$('input[name=_token]').val());

        $(CSSSelectorForm+' input[data-inputmask]').each(function (){
            let indexKey=$(this).attr('name');
            if(ajaxData.get(indexKey)){
                ajaxData.set(indexKey,ajaxData.get(indexKey).replace(/[_ ]+$/g,""));
            }
        });
        $.each(ajaxData.getAll('supplier'),function(key,value){
            ajaxData.append('supplier[]',value);
        })
        return ajaxData;
    }
    this.construct(options, ProfitCenterItem);

}
