const common_helper = {
    globalAjaxRequest : async (url,method,data = {})=>{
        $('#spinner').show();
        let response = {}
        try {
            response = await $.ajax({
                type: method,
                url: url,
                data: data
            })
            if (response) {
                $('#spinner').hide();
            }
        }catch (e) {
            $('#spinner').hide();
        }
        return response;
    },
    swalAleart:(html_content,iconclass,width,allowOutsideClick,title,showConfirmButton,showCancelButton,confirmButtonText,cancelButtonText)=> {
                   return  Swal.fire({
                            title:title,
                            icon: iconclass ,
                            text:'',
                            width: width,
                            html: html_content,
                            showCloseButton: true,
                            focusConfirm: false,
                            showConfirmButton: showConfirmButton,
                            allowOutsideClick:allowOutsideClick,
                            showCancelButton: showCancelButton,
                            confirmButtonText: confirmButtonText??'Ok',
                            cancelButtonText: cancelButtonText??'No',
                            confirmButtonColor:'#5cb85c',
                          });
                 },

    formValidate:(selector,fields,messages = {})=>{
        $(selector).validate({
            rules: fields,
            messages:messages
        });
    },

    youtubePopup:(selector,title='')=> {
        $(selector).magnificPopup({
            type: 'iframe',
            iframe: {
                markup:
                    '<div class="mfp-iframe-scaler">'+
                    '<div class="mfp-close"></div>'+
                    '<iframe class="mfp-iframe" allow="autoplay; encrypted-media"; ></iframe>'+
                    '<div class="mfp-bottom-bar">'+
                    '<div class="mfp-title" style="margin-top: -520px">'+title+'</div>'+
                    '</div>'+
                    '</div>',
                patterns: {
                    youtube: {
                        index: 'youtube.com',
                        id: 'v=',
                        src: 'https://www.youtube.com/embed/%id%?rel=0&autoplay=1'
                    }
                }
            },
        }).magnificPopup('open');
    },

    globalAjaxRequestAsync :async (url,method,data={},callback)=>{
         await $.ajax({
                async:true,
                type: method,
                url: url,
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                data: data,
                beforeSend:()=>{
                     $('#spinner').show();
                 },
                success:(result)=>{
                    console.log('ajax response',result);
                    return callback(result,data);
                },
                error:(jqXHR, textStatus, errorMessage)=> {
                    console.log('ajax error',jqXHR, textStatus, errorMessage);
                    return callback(errorMessage,data);
                },
                complete:()=>{
                    console.log('ajax complete');
                    $('#spinner').hide();
             }
            });
    },
    globalPasswordView :(selector,event)=> {
        event.preventDefault();
        let inputSelector=selector+' input';
        let iconSelector=selector+' i';
        if ($(inputSelector).attr("type") === "text") {
            $(inputSelector).attr('type', 'password');
            $(iconSelector).addClass("fa-eye-slash");
            $(iconSelector).removeClass("fa-eye");
        } else if ($(inputSelector).attr("type") === "password") {
            $(inputSelector).attr('type', 'text');
            $(iconSelector).removeClass("fa-eye-slash");
            $(iconSelector).addClass("fa-eye");
        }
    },

    globalRadioButtonClickEvent:(selector,checkValue,show_hide_selector)=>{
        let data = parseInt($(selector).val());
        let returnData=(data === checkValue);
        $(show_hide_selector).prop("disabled", !returnData);
    },

    saveCardCheckUncheck: (element, sibling)=> {
        $(sibling).prop('checked',false)
    },
    datePicker:(selector,
                format = 'yyyy-mm-dd',
                todayHighlight = true,
                startDate = new Date(),
                endDate = new Date())=>{
        $(selector).datepicker({
                    autoclose: true,
                    format: format,
                    todayHighlight: todayHighlight,
                    startDate: startDate,
                    endDate: endDate

    });
    },
    formatDate:()=> {
    let d = new Date(),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
},

    //summernote for tnymce editor
    init_summernote:(selector,placeholder)=>{
               $(selector).summernote({
                    placeholder: placeholder,
                   toolbar: [
                       [ 'style', [ 'style' ] ],
                       [ 'font', [ 'bold', 'italic', 'underline', 'clear'] ],
                       [ 'fontname', [ 'fontname' ] ],
                       [ 'fontsize', [ 'fontsize' ] ],
                       [ 'color', [ 'color' ] ],
                       [ 'para', [ 'ol', 'ul', 'paragraph', 'height' ] ],
                       [ 'table', [ 'table' ] ],
                       [ 'insert', [ 'link'] ],
                       [ 'view', [ 'undo', 'redo', 'help' ] ]
                   ],
                    tabsize: 2,
                    height: 400,
                    callbacks: {
                        // onImageUpload: function(files) {
                        //     uploadFile(files[0],item_count);
                        // }
                    }
                });
         },

     allChecked:(e,selector)=>{

         $('input:checkbox').prop('checked',e.checked);

         let checkedData = $("[name='"+selector+"']:checked");

         let alldelete = false;

         if(checkedData.length === 0){
             alldelete = true;
         }

         $('#btnDeleteMultipleClient').prop('disabled',(alldelete));
         $('#btnDeleteMultipleEmployee').prop('disabled',(alldelete));


     },
    // fileSizeValidation: (fileSize,selector,max_fileSize) => {
    //     let max_size = max_fileSize / 1024;
    //     let file = fileSize / 1024/1024 ;
    //     let text = 'File size cannot be greater than '+max_size+'MB';
    //     if (file > max_size) { // 1M
    //         Swal.fire({icon: 'error',title: text,width: 450});
    //         $(selector).val('');
    //     }
    // },
    fileSizeValidation : (event,max_fileSize)=>{
        let file_type = event.files[0].type;
        let file_size = event.files[0].size; // current file size in byte
        let selector =  $('#'+event.id);
        let max_size = max_fileSize / 1024; //max file size in kb to mb
        let current_file_size = file_size / 1024/1024 ; //current file size convert to mb
        let text = 'File size cannot be greater than '+max_size+'MB';
        let text_type = 'Oops! Please upload a jpeg or Png type of image only.';
        if(file_type === 'application/pdf' || file_type === 'application/x-zip-compressed' )
        {
            Swal.fire({icon: 'error',title: text_type,width: 450});
            $(selector).val('');
            return 0;
        }
        if (current_file_size > max_size) { // 1M
            Swal.fire({icon: 'error',title: text,width: 450});
            $(selector).val('');
            return 0;
        }
    },
    fileValidation : (event,max_fileSize)=>{
        let file_type = event.files[0].type;
        let file_size = event.files[0].size; // current file size in byte
        let selector =  $('#'+event.id);
        let max_size = max_fileSize / 1024; //max file size in kb to mb
        let current_file_size = file_size / 1024/1024 ; //current file size convert to mb
        let text = 'File size cannot be greater than '+max_size+'MB';
        if (current_file_size > max_size) { // 1M
            Swal.fire({icon: 'error',title: text,width: 450});
            $(selector).val('');
            return 0;
        }
    },

    show_hide_textbox : (icon_id,...selectors)=> {

        let class_name = $(icon_id).attr("class");

        let type = 'text';
        let addClass = 'fa-eye';
        let removeClass = 'fa-eye-slash';
        let remove_image_view_class = 'image-view-none';
        let add_image_view_class = '';
        let session_data = 0;

        if (class_name === 'fa fa-eye') {
            type = 'password';
            addClass = 'fa-eye-slash';
            removeClass = 'fa-eye';
            remove_image_view_class = '';
            add_image_view_class = 'image-view-none';
            session_data = 1;
        }

        selectors.forEach(function (item,index ){
            $(selectors[index]).attr('type', type);
        })

        $(icon_id).removeClass(removeClass);
        $(icon_id).addClass(addClass);

        $('#identity_proof_doc_id,#ssn_doc_id,#state_doc_id,#other_doc_id').removeClass(remove_image_view_class);
        $('#identity_proof_doc_id,#ssn_doc_id,#state_doc_id,#other_doc_id').addClass(add_image_view_class);

        return session_data;
    },

    validDate:(dValue) =>{
                if (dValue == '') dValue = $('#exp_date').val();
                var result = false;
                dValue = dValue.split('/');
                var pattern = /^\d{2}$/;
                var pattern1 = /^\d{4}$/;
                if (dValue[0] < 1 || dValue[0] > 12)
                    result = true;

                if (!pattern.test(dValue[0]) || !pattern1.test(dValue[1]))
                    result = true;

                if (dValue[2])
                    result = true;

                if (result) {
                    alert("Please enter a valid date in MM/YYYY format.");
                    $('#exp_date').val('');
                    return false;
                } else {
                    return true;
                }
        },

    modalView : (url,type,targetModal) => {
        common_helper.globalAjaxRequestAsync( url ,'POST',{ type: type,targetModal:targetModal },common_helper.modalviewcallback);
    },

    modalviewcallback : (result,data)=>{

        if(result){

            $('#modal_target').html(result);

            //This shows the modal
            $('#'+ data.targetModal).modal('show');
        }
    }
}
