let storedFile = [];
var thum = "";

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

$("body").on("click", ".up-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;
		}
	}

}


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"
});

function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg
}

function save_product() {

	var array=[];
	

	var input = document.getElementsByClassName('valid')
	for (var i = 0; i < input.length; i++) {
		console.log(input[i].value)
		if(input[i].value==''){
			 array.push(input[i]) 
		}
	}
	console.log(array)

	$('#save_btn').html(`Image Compress & Saving <i class="material-icons fa-spin">autorenew</i>`).attr('disabled', true)
	let errorClass = document.getElementsByClassName('error');
	for (var i = 0; i < errorClass.length; i ++) {
		errorClass[i].style.visibility = 'hidden';
	}
	let success=true;
	var title = document.getElementById('title')
	var brand = document.getElementById('brand')
	var discount = document.getElementById('discount')
	var delivery = document.getElementById('delivery')

	var cat = document.getElementById('category')
	var sub_cat = document.getElementById('sub_categories')
	var desc = CKEDITOR.instances.description.getData()
	var spec = CKEDITOR.instances.spec.getData()
	var price = document.getElementById('price')
	var quan = document.getElementById('quan')
	var coupon_type = document.getElementById('coupon_type')
	var cashback = document.getElementById('cashback')
	var img = document.getElementById('fileElem').files
	
	if(title.value == ''){
		printError("nameErr", "Please enter your product title");
		document.getElementById('nameErr').style.visibility=""
		success=false
	}
	 if(cat.value == "Choose Category"){
		printError("catErr", "Please enter your category");
		document.getElementById('catErr').style.visibility=""
		success=false
	}
	  if(!sub_cat.value){
		printError("subErr", "Please enter your sub category");
		document.getElementById('subErr').style.visibility=""
		success=false
	}
	if(!desc){
		printError("descriptionErr", "Please enter your product description");
		document.getElementById('descriptionErr').style.visibility=""
		success=false
	}
	 if(!price.value){
		printError("priceErr", "Please enter your product price");
		document.getElementById('priceErr').style.visibility=""
		success=false
	}
	if(img.length == 0){
		printError("imageErr", "Please upload your product picture");
		document.getElementById('imageErr').style.visibility=""
		success=false
	}
	if(success !== true){
		document.getElementById(array[0].id).focus()
		return false
	}

	let pic = document.getElementById('fileElem').files
	var formData = new FormData();
	formData.append('name',title.value)
	formData.append('own_refer_id', document.getElementById('own_refer_id').value)
	
	formData.append('company', brand.value)
	formData.append('color_id', $("#color").val())
	formData.append('size_id', $("#size").val())
	formData.append('cat', cat.value)
	formData.append('subCat', sub_cat.value)
	formData.append('desc', desc)
	formData.append('spec', spec)
	formData.append('price', price.value)
	formData.append('discount', discount.value)
	formData.append('delivery', delivery.value)
	formData.append('quan', 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)

	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.append('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 => {
		let save_btn = document.getElementById("_btn")
		let loading = document.getElementById('loading')
		loading.className='fa fa-refresh fa-spin'
		save_btn.setAttribute("disabled", true)
		console.log("all compress complete")
		
		for (var pair of formData.entries()) {
			console.log(pair[0]+ ', ' + pair[1]);
		}
		axios({
			method: 'post',
			url: 'https://myadmin.mali-mart.com/api/store-product',
			data: formData
		}).then(r => {
		
			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 successfully saved.</div>';
			if(r.data.success)
                {
				        //$(".alertMsg").html(alertMsg);
						 loading.className=''
				  save_btn.setAttribute("disabled", false)
				  alert('Success! Merchant Product successfully saved.')
				  window.location.reload();
				}
				console.log(r.data)	 					
			
		})
			.catch(e => [
				console.log('Eroor'),
				
			])
	})

}

