TYPES = ['base', 'second', 'sour', 'mixer']

$(document).ready(function() {
	for (ingredient_type of TYPES) {
		loadSelect(ingredient_type);
	}
	$('select').on('change', function () {
		onSelectChange();
	})
})

function loadSelect(ingredient_type) {
	$.get(`/api/ingredients/${ingredient_type}`, function (data) {
		$(`select#${ingredient_type}`).append($('<option>', {value: 0, text: "Select..."}))
		for (ingredient of data) {
			$(`select#${ingredient_type}`).append($('<option>', {value: ingredient, text: ingredient}))
		}
	})
}

function onSelectChange() {
	// Could sort-of do this with `TYPES.map(function (type) {...}`, but that wouldn't be able
	// to detect "are all select's filled-in?"
	combo_id = '';
	for (ingredient_type of TYPES) {
		val = $(`select#${ingredient_type}`).val()
		if (val == 0) {
			console.log(`DEBUG - found null value for ${ingredient_type}`)
			return // Don't do anything if any select isn't filled in
		}
		combo_id += '_' + val;
	}
	combo_id = combo_id.slice(1) // Drop the leading underscore
	data = $.get(`api/combination/${combo_id}`, function (data) {
		console.log(`Called for ${combo_id}`);
		console.log(data);

		$('#results-div').slideDown();
		$('#results-name').html(data[0]);
		if (data[1] != "") {
			$('#more-info-span').html(data[1]);
			$('#more-info-div').slideDown();
		} else {
			$('#more-info-span').html("");
			$('#more-info-div').slideUp();
		}

	})
}