
jQuery(document).ready(
    function($) {
        var img_upload_button = $('.wosmpl_upload_image_button');
        var img_viewer = $('#wosmpl_upload_viewer');
        var up_file = null;
        //take a single JavaScript File object
        function getFile(file) {
            var reader = new FileReader();
            return new Promise((resolve, reject) => {
                reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
                reader.onload = function () {

                    let base64StringFile = reader.result;

                    resolve({
                        base64: base64StringFile,
                        name: file.name,
                        type: file.type
                    });
                }
                reader.readAsDataURL(file);
            });
        }


        top.wosmpl_show_file = function() {
            var input = document.getElementById('wosml_img_selector');
            if (input.files.length > 0) {
                var file = input.files[0];
                getFile(file).then((customJsonFile) => {
                     up_file = customJsonFile.base64;
                     img_viewer.attr('src',customJsonFile.base64);
                     img_upload_button.show();

                });

            }

        }

        top.wosmpl_upload_file = function() {
            var clicked = $(this);
            $.post(wosmpl_ajax_obj.ajax_url, {         //POST request
                    _ajax_nonce: wosmpl_ajax_obj.nonce,     //nonce
                    action: "wosmpl_upload_file",            //action
                    file : up_file
                }, function(data) {                    //callback
                    if (data.error) {
                        //
                    } else {
                        clicked.closest('.upload').find('input[type="hidden"]').val(data.file_url);
                        img_upload_button.hide();
                    }
                }
            );
        }

    }
);
