/*
KKART
http://kkart.com/
(c) Kkart Team
*/

// Handle downloadable files of a product
function pagelayer_elp_downloadable_files(row, prop){
	
	var downloadable_files,
	data = {
		names : new Array(),
		hashes : new Array(),
		urls : new Array(),
	}, 
	downloadFileHTML = `<div class="kkart-download-file-div">
		<div class="kkart-add-new-downloadable-file"><button>Add File</button></div>
	</div>`;
		
	row.append(downloadFileHTML);
	
	var setFileData = function(jEle, isWpMedia = false) {
		
		var inputWrap = jEle.closest('.kkart-download-file-inputs'),
		fileNameHolder = jEle.closest('.kkart-download-file-tab-wrapper').find('.kkart-download-file-name-holder');
		
		var file = {
			urls : inputWrap.find('[name="download-file-url"]').val(),
			names : inputWrap.find('[name="download-file-name"]').val(),
			hashes : parseInt(inputWrap.find('[name="download-file-hash"]').val()),
		};
		
		var oldHash = parseInt(inputWrap.data('file-id')),
		isNameInput = jEle.attr('name') == 'download-file-name';
		
		// Create new hash if URL input changes
		if(!isWpMedia && !isNameInput){

			do{
				file.hashes = Math.floor(1000 + Math.random() * 9000);
			} while(data.hashes.indexOf(file.hashes) > -1);
			
			inputWrap.find('[name="download-file-hash"]').val(file.hashes);
		}
		
		var indexOfHash = data.hashes.indexOf(file.hashes);
		
		// Checks if the a file is being changed
		if(indexOfHash == -1 && !pagelayer_empty(oldHash)) {
			indexOfHash = data.hashes.indexOf(oldHash);
		}
		
		// If name is being added but url is empty dont save
		if(isNameInput && !file.urls) {
			return;
		}
		
		for(var input in file) {
			if(indexOfHash > -1) {
				data[input][indexOfHash] = file[input];
			} else{
				data[input].push(file[input]);
			}
		}
		
		if(!pagelayer_empty(file.names)) {
			fileNameHolder.text(file.names);
		}
		
		// Update data
		inputWrap.attr('data-file-id', file.hashes);
		_pagelayer_set_atts(row, data);
		
	}
	
	var generateTab = function(file = []) {
		return `<div class="kkart-download-file-tab-wrapper">
			<div class="kkart-download-file-tab">
				<div>
				<span class="kkart-download-file-name-holder">${file.name ? file.name : 'File'}</span>
				</div>
				<span><i class="pli pli-trashcan"></i></span>
			</div>
			<div class="kkart-download-file-inputs" data-file-id="${file.hash ? file.hash : ''}">
				<input type="hidden" name="download-file-hash" value="${file.hash ? file.hash : ''}">
				<div class="kkart-download-file-name">
					<label for="kkart-download-file-name">File Name</label>
					<input type="text" placeholder="File Name"  name="download-file-name" value="${file.name ? file.name : ''}"/>
				</div>
				<div class="kkart-download-file-url">
					<label for="kkart-download-file-name">File URL</label>
					
					<div class="kkart-downloadable-file-wrap">
						<input type="url" placeholder="http://"/ name="download-file-url" value="${file.url ? file.url : ''}">
						<i class="fa fa-upload kkart-downloadable-button" aria-hidden="true"></i>
					</div>
				</div>
			</div>
		</div>`;
	}
	
	// Remove file
	var removeFile = function(id){
		var removalIndex = data.hashes.indexOf(parseInt(id));
		
		data.hashes.splice(removalIndex, 1);
		data.urls.splice(removalIndex, 1);
		data.names.splice(removalIndex, 1);
		
		_pagelayer_set_atts(row, data);
	}
	
	// Renders file tabs html
	if(! pagelayer_empty(prop.el.atts._downloadable_files)){
		
		downloadable_files = prop.el.atts._downloadable_files;

		if(! pagelayer_empty(downloadable_files)) {
			for(var [index, fileOpts] of Object.entries(downloadable_files) ) {
				data[index] = Object.values(fileOpts);
			}
		}
		
		var input_files = [];
		if(!pagelayer_empty(downloadable_files.hashes)){
			
			for(var [index, hash] of Object.entries(downloadable_files.hashes)) {
				var single_file = [];
				
				single_file['hash'] =  downloadable_files.hashes[index];
				single_file['name'] =  downloadable_files.names[index];
				single_file['url']	=  downloadable_files.urls[index];
				input_files.push( single_file );
			}
		}
		
		// Render file tab
		input_files.forEach(function(file) {
			var addBtnDiv = row.find('.kkart-add-new-downloadable-file');
			addBtnDiv.before(generateTab(file));
		});
	}
	
	// Add event listener to upload btn and remove icons
	pagelayer.$$('.kkart-add-new-downloadable-file > button').on('click', function() {
		
		var addBtnDiv = jQuery(this).closest('.kkart-add-new-downloadable-file');
		
		addBtnDiv.before(generateTab());
	});
	
	
	row.on('change','.kkart-download-file-inputs input', function() {
		setFileData(jQuery(this));
	});

	row.on('click', '.kkart-download-file-tab', function() {
		jQuery(this).next('.kkart-download-file-inputs').slideToggle('slow');
	});
	
	row.on('click', '.pli-trashcan', function() {
		var wrapper = jQuery(this).closest('.kkart-download-file-tab-wrapper'),
		hash = wrapper.find('[name="download-file-hash"]').val();
		
		// Remove hash from array list
		if(!pagelayer_empty(hash)) {	
			removeFile(hash);
		}
		
		wrapper.remove();
	});
	
	row.on('click', '.kkart-downloadable-button', function(e){
	
		e.preventDefault();
		
		var jEle = jQuery(this);
		var frame = wp.media({
			title: 'Select a File',
			frame: 'select',
			button:{
				text: 'Insert'
			},
			multiple: false
		});
		
		frame.on('select', function(){
			var attachement = frame.state().get('selection').first().toJSON();
			
			if(attachement) {
				var inputWrapper = jEle.closest('.kkart-download-file-inputs');
				
				//TODO: Direct update array
				inputWrapper.find('[name="download-file-name"]').val(attachement.name);
				inputWrapper.find('[name="download-file-hash"]').val(attachement.id); //TODO change id with hash
				inputWrapper.find('[name="download-file-url"]').val(attachement.url);
				
				setFileData(jEle, true);
			}					
		});
		frame.open();
	});
}

// The Checkbox property
function pagelayer_elp_variable_porduct(row, prop){
	// TODO for variable products 
}
