require('./bootstrap');


//----------------------------------------------------------------------
/*
Helper function
*/
window.getMonday=function(date,dateStr) {
    if(dateStr){
        date = new Date(dateStr);
    }

    let day = date.getDay(),
        diff = date.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
    return new Date(date.setDate(diff));
}
window.debug=function (txt)
{
    try {
        console.log(txt);
    }
    catch(e){}
};

window.buildFormData=function(formData, data, parentKey) {
    if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
        Object.keys(data).forEach(key => {
            buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
        });
    } else {
        const value = data == null ? '' : data;

        formData.append(parentKey, value);
    }
}

window.jsonToFormData=function(data) {
    const formData = new FormData();

    buildFormData(formData, data);

    return formData;
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1)
}

window.arrayRemove=function(arr, value) {

    return arr.filter(function(ele){
        return ele != value;
    });
}
window.getRandomInt=function (max=Number.MAX_SAFE_INTEGER,min=0) {
    debug(max);
    debug(min);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

window.setImageFromLocal=function(input,targetImgCssSelector) {
    if (input.files && input.files[0]) {
        let reader = new FileReader();
        reader.onload = function (e) {
            $(targetImgCssSelector).attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

require('./latinise');

/*
disable back button
 */
$(function() {
    if (window.history && window.history.pushState) {
        window.history.pushState('', null, window.location.href);
        $(window).on('popstate', function(event) {
            // alert('Back button was pressed.');
            //document.location.href = '#';
            window.history.pushState('', document.title, window.location.href);
            //console.log('mevagy');
            event.stopPropagation();
        });
    }
});
//----------------------------------------------------------------------
/*
init custom radio buttons
 */
window.initRadioButtons=function (Options){
    let Opts = {
        onChange: function (value,node) {
        },
    };

    $.extend(Opts, Options);

    $('.customRadioBtnGroup .active').each(function() {
        let activeValue = $(this).data('title');
        let target = $(this).data('toggle');
        $('input[name='+target+']').prop('value', activeValue);
    });

    $('.customRadioBtnGroup a').unbind('click');
    $('.customRadioBtnGroup a').bind('click',function(){
        let sel = $(this).data('title');
        let tog = $(this).data('toggle');
        $('input[name='+tog+']').prop('value', sel);
        $('a[data-toggle="'+tog+'"]').not('[data-title="'+sel+'"]').removeClass('active').addClass('notActive');
        $('a[data-toggle="'+tog+'"][data-title="'+sel+'"]').removeClass('notActive').addClass('active');
        Opts.onChange(sel,tog);
    });
}

//----------------------------------------------------------------------
//  Defaults
//----------------------------------------------------------------------
$.extend( true, $.fn.dataTable.defaults, {
    language: {
        url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
    },
    lengthMenu: [
        [ 10, 25, 50, -1 ],
        [ '10 sor', '25 sor', '50 sor', 'Összes' ]
    ],
    buttons:{
        dom:{
            button:{
                className:'fg-button ui-button dataTableHeaderButtons'
            }
        },
    },
    dom: '<"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix ui-corner-tl ui-corner-tr"lBfr>'+
        't'+
        '<"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix ui-corner-bl ui-corner-br"ip>',

} );
Inputmask.extendDefinitions({
    'x': {
        validator: "[\.,-áéíóöőúàèìòùüűÁÉÍÓÖŐÚÀÈÌÒÙÜŰA-Za-z0-9 ]",
        //cardinality: 1
    }
});


//----------------------------------------------------------------------
Toast.enableTimers(false);
$.fn.select2.defaults.set('language', 'jp');
window.select2CreateTag=function (params){
    var term = $.trim(params.term);
    var count = 0
    var existsVar = false;
    //check if there is any option already
    if($('#keywords option').length > 0){
        $('#keywords option').each(function(){
            if ($(this).text().toUpperCase() == term.toUpperCase()) {
                existsVar = true
                return false;
            }else{
                existsVar = false
            }
        });
        if(existsVar){
            return null;
        }
        return {
            id: params.term,
            text: params.term,
            newTag: true
        }
    }
    //since select has 0 options, add new without comparing
    else{
        return {
            id: params.term,
            text: params.term,
            newTag: true
        }
    }

}

window.ajaxErrorHandler= function (xhr, ajaxOptions, thrownError){
    debug(this);
    console.error(xhr);
    console.error(ajaxOptions);
    console.error(thrownError);

    // Biztonsági ellenőrzés – ha nincs responseJSON (pl. HTML válasz)
    if (!xhr.responseJSON) {
        ajaxErrorFieldHandler({'detail': 'Váratlan szerverhiba. Kérjük próbálja újra később.'});
        return;
    }

    // Validációs hibák (422) – ezeket részletesen megjelenítjük
    if (xhr.responseJSON.errors) {
        console.error("d2---------------");
        if("jsonapi" in xhr.responseJSON){
            ajaxErrorFieldHandlerJsonAPI(xhr.responseJSON.errors);
        }else{
            ajaxErrorFieldHandler(xhr.responseJSON.errors);
        }
    }
    // Egyedi referencia kódos hiba (500, stb.)
    else if (xhr.responseJSON.error_ref) {
        console.error("error_ref: " + xhr.responseJSON.error_ref);
        Toast.create({
            title: "Szerverhiba",
            message: "Váratlan hiba történt a feldolgozás során.<br>" +
                     "<small>Hivatkozási kód: <strong>" + xhr.responseJSON.error_ref + "</strong></small><br>" +
                     "<small>Kérjük, ezt a kódot adja meg a hibajelentésben.</small>",
            status: TOAST_STATUS.DANGER,
            timeout: 0
        });
    }
    // 404
    else if (xhr.status == 404) {
        console.error("d3---------------");
        ajaxErrorFieldHandler({'detail':'Nincs ilyen elem.'});
    }
    // Egyéb ismeretlen hiba
    else {
        console.error("d4---------------");
        ajaxErrorFieldHandler({'detail':'Általános hiba.'});
    }
}
window.ajaxErrorFieldHandlerJsonAPI= function (errors, container) {
    console.error("d6---------------");
    let toastBodyHtml = '';
    let toastTitle = 'Hiba';
    console.error(errors);
    $.each(errors, function (index, value) {
        console.error(value);
        toastTitle = 'Hiba';
        toastBodyHtml = '';
        if("title" in value){
            toastTitle=value.title;
        }
        if("detail" in value){
            toastBodyHtml += '<div>' + value.detail + '<div>';
        }
        Toast.create({
            title: toastTitle,
            message: toastBodyHtml,
            status: TOAST_STATUS.DANGER,   // SUCCESS (zöld)
            timeout: 10000
        });
    });
}
window.ajaxErrorFieldHandler = function (errors, container) {
    console.error("d5---------------");
    console.error(errors);
    let toastBodyHtml = '';
    $.each(errors, function (index, value) {
        toastBodyHtml += '<div>' + value + '<div>';
    });

    Toast.create({
        title: "Hiba!",
        message: toastBodyHtml,
        status: TOAST_STATUS.DANGER,   // SUCCESS (zöld)
        timeout: 10000
    });
}
$.ajaxSetup({
    error:ajaxErrorHandler,
});
/*
datepicker afterShow function
 */
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
    $.datepicker._updateDatepicker_original(inst);
    let afterShow = this._get(inst, 'afterShow');
    if (afterShow)
        afterShow.apply((inst.input ? inst.input[0] : null));  // trigger custom callback
}


//----------------------------------------------------------------------
window.EmegrendelesDefaults={
    datatableActionButtonClickCallBack: function () {},
    datatableAddRowTrashButton: function (id,args) {
        return '<button type="button" class="btn btn-sm btn-danger buttonDelete" data-buttonType="delete" data-toggle="tooltip" data-placement="bottom" title="Törlés">' +
            '<span class="fas fa-trash"></span>' +
            '</button>'

    },
    datatableAddRowEditButton: function (args) {
        let title='Adatok';
        if(typeof args[1].title!=="undefined"){
            title=args[1].title;
        }
        return '<button type="button" class="btn btn-sm btn-info buttonEdit"  data-buttonType="edit" data-toggle="tooltip" data-placement="bottom" title="'+title+'">' +
            '<span class="fas fa-pencil-alt"></span>' +
            '</button>'

    },
    datatableAddRowViewButton: function (id,args) {
        return '<button type="button" class="btn btn-sm btn-outline-secondary dataTableRowButton buttonView"  data-buttonType="view" data-toggle="tooltip" data-placement="bottom" title="Megtekint">' +
            '<span class="fas fa-eye"></span>' +
            '</button>'

    },
    datatableAddRowAttachmentButton: function (id,args) {
        return '<button type="button" class="btn btn-sm btn-outline-dark dataTableRowButton buttonAttachment"  data-buttonType="attachment" data-toggle="tooltip" data-placement="bottom" title="Csatolmány">' +
            '<span class="fas fa-paperclip"></span>' +
            '</button>'

    },
    datatableCustomHeadButtonClickCallBack:function (args) {
        console.log(args);
    },

    afterLoadMainContent:function (args) {
        console.log(args);
    },


};

if(typeof DataModel==='undefined'){
    class DataModel{
        /*
         * Variables accessible
         * in the class
         */
        Opts = {
            active: false,
        };

        /*
         * Constructor
         */
        constructor (data,options) {
            $.extend(this, data);
            $.extend(this.Opts, options);
        };

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

        getData(index){
            if(index){
                return this[index];
            }else{
                return this;
            }
        }
    };
    window.DataModel=DataModel;
}


window.Emegrendeles = function (options) {

    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        myVar: 'Emegrendeles value',
        datatableAddRowTrashButton:{},
        datatableAddRowEditButton:{},
        datatableActionButtonClickCallBack:{},
        datatableRowActionButtonClickCallBack:{},
        datatableCustomHeadButtonClickCallBack:{},
        afterLoadMainContent:{},
        Url:{},
    };

    const PublicVar={};
    let PublicVar2={'asd':'21'};
    let ApiToken=null;
    let root=this;
    /*
     * Constructor
     */
    this.construct = function (options) {
        //$.extend(Opts, options);
        console.log(this.constructor.name+' constructor called');
        $.extend(Opts, window.EmegrendelesDefaults, options);
    };

    this.setOpts=function(options){
        $.extend(Opts, options);
    }

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

    this.datatableAddRowTrashButton=function (){
        return Opts.datatableAddRowTrashButton(arguments);
    }
    this.datatableAddRowEditButton=function (){
        return Opts.datatableAddRowEditButton(arguments);
    }

    this.datatableAddRowViewButton=function (){
        return Opts.datatableAddRowViewButton(arguments);
    }
    this.datatableAddRowAttachmentButton=function (){
        return Opts.datatableAddRowAttachmentButton(arguments);
    }

    this.afterLoadMainContent=function (){
        return Opts.afterLoadMainContent(arguments);
    }

    this.datatableActionButtonClickCallBack=function (){
        return Opts.datatableActionButtonClickCallBack(arguments);
    }
    this.datatableRowActionButtonClickCallBack=function (){
        return Opts.datatableRowActionButtonClickCallBack(arguments);
    }

    this.datatableAddRowAction=function (CSSSelector){
        if(!CSSSelector){
            return;
        }
        $(CSSSelector+' tr button').off('click');
        $(CSSSelector+' tr button').on('click',APP.datatableRowActionButtonClickCallBack );
    }

    this.datatableCustomHeadButtonClickCallBack=function (){
        return Opts.datatableCustomHeadButtonClickCallBack(arguments);
    }

    /*
     * Public method
     * Can be called outside class
     */
    this.myPublicMethod = function () {
        console.log(Opts);

        myPrivateMethod();
    };

    this.setApiToken = function (token) {
        root.ApiToken=token;
    };

    this.getApiToken = function () {
        return root.ApiToken;
    };

    /*
     * Private method
     * Can only be called inside class
     */
    const myPrivateMethod = function () {
        console.log('accessed private method');
    };

    /**
     * @param {string} itemName
     */
    this.setActiveNavBarItem=function(itemName){
        $('.speedButtonNavBar li').removeClass('selected');
        $('.speedButtonNavBar li.iconholderModul'+itemName).addClass('selected');
        return this;
    }

    this.getActiveNavBarItem=function(){
      return $('.speedButtonNavBar .selected').find('a').data('name');
    }

    this.clearArchiveModuleDataTableState=function(){
        if(APP.OrderArchiveModule!=undefined ){
            console.log('APP.OrderArchiveModule');
                console.log('clear');
                APP.OrderArchiveModule.dataTable.state.clear();
        }

    }
    this.navBarItemBeforepost=function (){
        console.log('navBarItemBeforepost');
        if(root.getActiveNavBarItem()!=='activeOrder'){
            root.clearArchiveModuleDataTableState();
        };

    }

    this.navBarItemAfterPost=function (){
    }

    this.initNavBar=function (){
        $(".speedButtonNavBar a:not([data-target=_blank]):not([data-no-ajax])").bind('click',function (event){
            console.log($(this).data().name);
            if($(this).data('big-icon')){
                $(".speedButtonNavBar").removeClass('smallicons');
            }else{
                $(".speedButtonNavBar").addClass('smallicons');
            }

            root.setActiveNavBarItem($(this).data().name);
            event.preventDefault();
        });
        $(".speedButtonNavBar a:not([data-target=_blank]):not([data-no-ajax])").ajaxlink({
            target:$('.mainContent'),
            ajaxtype:'GET',
            afterpost:root.navBarItemAfterPost,
            beforepost:root.navBarItemBeforepost,
        });
        $(".speedButtonNavBar a[data-target=_blank], .speedButtonNavBar a[data-no-ajax]").bind('click',function(){
            root.clearArchiveModuleDataTableState();
        });
    }

    this.loadMainContent=function (url,data,callBack){

        if(!callBack){
            callBack=root.afterLoadMainContent;
        }else{
            console.log('van callback');
            console.log(callBack);
        }
        $('.mainContent').load(
            url,data,callBack
        );
    }
    /*
     * Pass options when class instantiated
     */
    this.construct(options);
};


/*
$.fn.ajaxlink = function(options){

};
import './ajaxLink';

* */
window.APP={};
$(document).ready(function (){
    console.log('ready doc');
    //$('.datepicker').datepicker();
    Mustache.tags = [ '[[', ']]' ];
    // = [ '<%', '%>' ];

});



