window.ContactPopUp = function (options,itemData) {

    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        active: false,
        array: [],
        onAfterSave: function () {
        },
        onClose: function () {
        },
    };
    let data = {};
    let root = this;
    /*
     * Constructor
     */
    this.construct = function (options,itemData) {
        console.log(' ContactPopUp constructor called');
    };

    this.init = function (options,itemData) {
        console.log(' ContactPopUp nit called');
        $.extend(Opts, options);
        $.extend(data, itemData);
        root.bindClickAction();
        $("select.contactType").select2({
            maximumSelectionLength: 1,
        });

    };

    this.clearData=function (){
        data={};
        root.renderForm();
    }

    this.setData=function (itemData){
        $.extend(data, itemData);
    }

    this.show=function () {
        $('.contactModal').modal().show();
    }

    this.renderForm=function (){
        $('.contactModal input').val('');
        $('.contactModal textarea').val('');
        $.each(data,function (key,value) {
            /*
                            console.log('key:'+key+' value:'+value);
                            console.log('.contactModal'+' *[name=contact'+$.ucFirst(key)+']');
            */
            $('.contactModal'+' *[name=contact'+$.ucFirst(key)+']').val(value);
        });
        if(data.type === undefined || data.type===null){
            $("select.contactType").select2().val();
        }else{
            $("select.contactType").select2().val(data.type.split(','));
        }

        $("select.contactType").select2().trigger('change');

    }

    this.loadData=function (contactId){
        console.log('loading id:'+contactId);
        $('.contactModal .spinnerDiv').removeClass('d-none');
        $('.contactModal .contactModalForm').addClass('d-none');
        $('.contactModal').modal().show();
        let url=APP.getOpts()["Url"]["contactPopup"]['show'];
        url=url.replaceAll('*contactId*',contactId);
        $.ajax({
            url: url,
            type: 'GET',
            headers: {
                'X-CSRF-TOKEN': APP.getApiToken()
            },
            success: function (data) {
                root.setData(data);
                root.renderForm();
                $('.spinnerDiv').addClass('d-none');
                $('.contactModalForm').removeClass('d-none');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                if (xhr.responseJSON.errors) {
                    ajaxErrorFieldHandler(xhr.responseJSON.errors);
                }else{
                    if(xhr.status==404){
                        ajaxErrorFieldHandler([{'detail':'Nincs ilyen elem.'}]);
                    }else{
                        ajaxErrorFieldHandler([{'detail':'Általános hiba.'}]);
                    }
                }
                $('.contactModal').modal('hide');
            },
        });
        return ;
        let contactData={
            id:76,
            name:'Miksóné Borbély Erzsébet',
            email:'szamlazas1@funkcio.hu',
            phone:'+36203407500'
        };
        root.setData(contactData);
        root.renderForm();
        $('.spinnerDiv').addClass('d-none');
        $('.contactModalForm').removeClass('d-none');

    }

    this.getOpts = function () {
        return Opts;
    }
    this.bindClickAction = function () {
        $('.contactModal .btn').unbind('click');
        $('.contactModal .buttonClose').bind('click', root.clickActionButtonClose);
        $('.contactModal .buttonSave').bind('click', root.clickActionButtonSave);
    }

    this.clickActionButtonClose = function (event) {
        console.log('click close');
        Opts.onClose(event, root.formDataToDataObjectAPICall());
    }


    this.saveContact = function (contactData) {
        let form = $('.contactModal form');
        let url=form.attr('action');
        let ajaxType='POST';
        if(contactData.id){
            url=APP.getOpts()["Url"]["contactPopup"]['update'];

                //'{{route("admin.contact.update","*contactId*")}}';
            url=url.replaceAll('*contactId*',contactData.id);
            ajaxType='PUT';
        }
        if(!contactData.status){
            contactData.status=APP.getOpts()["contactPopup"]['defaultStatus'];
        }

        $.ajax({
            url: url,
            type: ajaxType,
            headers: {
                'X-CSRF-TOKEN': APP.getApiToken()
            },
            data: contactData,
            success: function (data) {
                Opts.onAfterSave(data);
                $('.contactModal').modal('toggle');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                if (xhr.responseJSON.errors) {
                    ajaxErrorFieldHandler(xhr.responseJSON.errors);
                }
            },
        });

        return false;
    }

    this.clickActionButtonSave = function (event) {
        console.log('click save');
        let contactData = root.formDataToDataObjectAPICall(), savedData;
        if(savedData=root.saveContact(contactData)){
            Opts.onAfterSave(event, contactData);
            $('.contactModal').modal('toggle');
            return  true;
        }
        return false;
    }



    this.formDataToDataObjectAPICall = function () {
        let data = new FormData(document.querySelector('.contactModal form'));
        let formJSON = Object.fromEntries(data.entries());
        /*Multiselect or checkbox to array:
        formJSON.multiselectName = data.getAll('multiselectName');
        */
        $.each(formJSON, function (item, value) {
            formJSON[$.lcFirst(item.replace('contact', ''))] = value;
            delete formJSON[item];
        });
        if(formJSON.phone){
            formJSON.phone=formJSON.phone.replaceAll('_','');
        }
        if(formJSON.email){
            formJSON.email=formJSON.email.replaceAll('_','');
        }
        formJSON.type=$("select.contactType").select2().val();
        return formJSON;
    }

    this.construct(options,itemData);
}
