let storedFile = [];
var thum = document.getElementById("thumb").value;

$("body").on("click", ".fa-close", removeFile);

$("body").on("click", ".up-img > img", (e) => {
    $('.up-img').each(i => {
        $('.up-img').removeClass('thumb')
        $('.up-img > span').remove()
    })
    e.target.parentNode.classList.add('thumb')
    let thumbnail = document.createElement("span")
    thumbnail.innerHTML = "Thumbnail"
    thumbnail.className = "thumb_txt"
    e.target.parentNode.insertBefore(thumbnail, e.target.parentNode.firstChild)
    thum = e.target.parentNode.id
});

function preventDefaults(e) {
    e.preventDefault()
    e.stopPropagation()
}

function highlight(e) {
    dropArea.classList.add('highlight')
}

function unhighlight(e) {
    dropArea.classList.remove('highlight')
}

function handleDrop(e) {
    var dt = e.dataTransfer
    var files = dt.files

    handleFiles(files)
}

let uploadProgress = []
let progressBar = document.getElementById('progress-bar')

function initializeProgress(numFiles) {
    progressBar.value = 0
    uploadProgress = []

    for (let i = numFiles; i > 0; i--) {
        uploadProgress.push(0)
    }
}

function updateProgress(fileNumber, percent) {
    uploadProgress[fileNumber] = percent
    let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
    console.debug('update', fileNumber, percent, total)
    progressBar.value = total
}

function handleFiles(e) {
    files = e.files
    storedFile.push(...files);
    files = [...files]
    initializeProgress(files.length)
    //files.forEach(uploadFile)
    files.forEach(previewFile)
}

function previewFile(file) {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onloadend = function () {

    $('.up-img').each(i => {
        $('.up-img').removeClass('thumb')
        $('.up-img > span').remove()
    })

    let div = document.createElement('div')
    div.id = file.name
    div.className = 'up-img thumb'
    div.innerHTML = `<span class="thumb_txt">Thumbnail</span><i class="close_i material-icons fa fa-close"></i> <img src="${reader.result}">`
    thum=file.name
    document.getElementById('gallery').appendChild(div)
    }
}

function removeFile(e) {
    var file = e.target.parentNode.id;
    for (var i = 0; i < storedFile.length; i++) {
        if (storedFile[i].name === file) {
            storedFile.splice(i, 1);
            document.getElementById(e.target.parentNode.id).remove()
            break;
        }
    }

}
function del_pic(e) {

    if (confirm("Are sure to delete this picture ?")) {
        if (e.parentNode.classList.contains('thumb')) {
            $('.up-img').each(i => {
                $('.up-img').removeClass('thumb')
                $('.up-img > span').remove()
            })
            e.parentNode.parentNode.children[0].classList.add('thumb')
            let thumbnail = document.createElement("span")
            thumbnail.innerHTML = "Thumbnail"
            thumbnail.className = "thumb_txt"
            e.parentNode.parentNode.children[0].insertBefore(thumbnail, e.parentNode.parentNode.children[0].firstChild)
            thum = e.parentNode.parentNode.children[0].id
        }

        axios({
            method: 'delete',
            url: 'https://myadmin.mali-mart.com/api/product-delete-pic',
            data: {
                id: document.getElementById("pdt_id").value,
                pic: e.parentNode.id
            }
        }).then(r => {

            r.data == 'success' && e.parentNode.remove();
        })
    }
}


function save_product() {

    $('#save_btn').html(`Saveing <i class="material-icons fa-spin">autorenew</i>`).attr('disabled', true)

    let pic = document.getElementById('fileElem').files
	var coupon_type = document.getElementById('coupon_type')
	var cashback = document.getElementById('cashback')
    var formData = new FormData();
 
    formData.append('name', document.getElementById('title').value)
	formData.append('company', document.getElementById('brand').value)
	formData.append('color_id', $("#color").val())
	formData.append('size_id', $("#size").val())
	formData.append('cat', document.getElementById('category').value)
	formData.append('subCat', document.getElementById('sub_categories').value)
	formData.append('desc', CKEDITOR.instances.description.getData())
	formData.append('spec', CKEDITOR.instances.spec.getData())
	formData.append('price', document.getElementById('price').value)
	formData.append('discount', document.getElementById('discount').value)
	formData.append('delivery', document.getElementById('delivery').value)
	formData.append('quan', document.getElementById('quan').value)
	formData.append('vdo', document.getElementById('vdo').value)
	formData.append('coupon_type', coupon_type ? coupon_type.value : 0)
	formData.append('cashback', cashback ? cashback.value : 0)


    formData.append('id', document.getElementById('pdt_id').value)
    formData.append('thum', thum)


    var imageCompressor = new ImageCompressor;

    const config_1280 = {
        checkOrientation: true,
        maxWidth: 1280,
        maxHeight: undefined,
        minWidth: 0,
        minHeight: 0,
        width: undefined,
        height: undefined,
        quality: 0.8,
        mimeType: '',
        convertSize: 5000000,
    };

    const config_300 = {
        checkOrientation: true,
        maxWidth: 300,
        maxHeight: undefined,
        minWidth: 0,
        minHeight: 0,
        width: undefined,
        height: undefined,
        quality: 0.8,
        mimeType: '',
        convertSize: 5000000,
    };
    const config_80 = {
        checkOrientation: true,
        maxWidth: 80,
        maxHeight: undefined,
        minWidth: 0,
        minHeight: 0,
        width: undefined,
        height: undefined,
        quality: 0.8,
        mimeType: '',
        convertSize: 5000000,
    };

    function file_compress(file) {
        return new Promise((resolve, reject) => {
            //send thumbnail arr index
            file.name === thum && formData.set('thum' , storedFile.indexOf(file))
            imageCompressor.compress(file, config_1280)
                .then(r => {
                    console.log('main img complete')
                    formData.append('pic' + storedFile.indexOf(file), r)
                    //300px img
                    imageCompressor.compress(file, config_300)
                        .then(r => {
                            console.log('min img complete')
                            formData.append('min' + storedFile.indexOf(file), r)
                            //80px img
                            imageCompressor.compress(file, config_80)
                                .then(r => {
                                    console.log('tmb img complete')
                                    formData.append('tmb' + storedFile.indexOf(file), r)
                                    resolve(file) //done
                                })
                        })
                })
        })
    }

    let result = storedFile.reduce((accumulatorPromise, nextID) => {
        return accumulatorPromise.then(() => {
            return file_compress(nextID);
        });
    }, Promise.resolve());

    result.then(e => {
        console.log("all compress complete")
        for (var pair of formData.entries()) {
                console.log(pair[0]+ ', ' + pair[1]);
            }
        axios({
                method: 'post',
                url: $("#edit_form").attr('action'),
                data: formData
            }).then(r => {
                console.log(r.data);
                
                    if(r.data.success)
                    {
                        var alertMsg = '<div class="alert alert-success fade in alert-dismissible" style="margin-top:18px;opacity:1 !important"><a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">'+'*'+'</a><strong>Success!</strong> Merchant Product Update successfully done.</div>';
				        $(".alertMsg").html(alertMsg);
                    } 
              
            })
            .catch(e => [
                console.log('Eroor')
            ])
    })
}



CKEDITOR.replace('description', {
    height: 200,
    removeButtons: "Image,Source,About"
});

CKEDITOR.replace('spec', {
    height: 150,
    extraPlugins: 'placeholder',
    removeButtons: "Unlink,Image,Source,About,Underline,Strike,Subscript,Superscript,List,BlockQuote"
});

