Source: core/Liqueur.js

import { Measure } from '../data/Measure.js';
import { Density } from '../data/Density.js';
import { CaloricContent } from '../data/CaloricContent.js';

import { Ingredient } from './Ingredient.js';
import { Water } from './Water.js';
import { Alcohol } from './Alcohol.js';
import { Syrup } from './Syrup.js';

import { Component } from './Component.js';
import { Composition } from './Composition.js';
import { Conversion } from './Conversion.js';

import { CalculationError } from './CalculationError.js';

/**
 * A union of syrup and alcohol solution.
 * Takes "sugar content" from syrup and "alcohol content" from alcohol
 * and creates a liqueur with both characteristics combined.
 * 
 * @extends {Ingredient}
 */
export class Liqueur extends Ingredient {
	composition = null;
	density = null;
	type = 'liqueur';
	/**
	 * Make a liqueur
	 *
	 * @constructor
	 * @param {(Alcohol|null)} [alcohol=null]
	 * @param {(Syrup|null)} [syrup=null]
	 *
	 * @example
	 * let CremeDeCassis = new Liqueur(
	 * 	new Alcohol(0.20, Measure.VV),
	 * 	new Syrup(0.400, Measure.WV),
	 * );
	 */
	constructor(alcohol, syrup) {
		super();
		let volume_left = 1000;
		this.composition = new Composition();

		if (syrup) {
			let sugar = new Component(
				new Syrup(1, Measure.WW),
				syrup.get(Measure.WV) * volume_left,
				Measure.G
			);
			let water_volume = (syrup.get(Measure.DENSITY) - syrup.get(Measure.WV)) / Density.WATER * 1000;
			volume_left = water_volume;
			if (volume_left < 0)
				throw new CalculationError('IMPOSSIBLE_COMBINATION');
			this.composition.add('sugar', sugar);
		}

		if (alcohol) {
			let target_abv = alcohol.get(Measure.VV) * (1000 / volume_left);
			if (target_abv > 1) {
				throw new CalculationError('IMPOSSIBLE_COMBINATION');
			}

			let real_alcohol = new Alcohol(target_abv * 100, Measure.ABV);

			this.composition.add('alcohol', new Component(
				real_alcohol,
				volume_left,
				Measure.ML
			));

		} else {
			this.composition.add('buffer', new Component(
				new Water(),
				volume_left,
				Measure.ML
			));
		}

		this.density = this.composition.total(Measure.G) / 1000;
	}
	/**
	 * Create from composition
	 * 
	 * @static 
	 * @param {Composition} composition
	 * 
	 * @returns {Liqueur}
	 */
	static fromComposition(composition) {
		let info = composition.info();
		let syrup = info.sugar_content > 0 ? new Syrup(info.sugar_content, Measure.WV) : null,
			alcohol = info.abv > 0 ? new Alcohol(info.abv, Measure.ABV) : null;
		return new Liqueur(
			alcohol, 
			syrup
		);
	}
	/**
	 * Get liqueur measurement
	 * 
	 * Available measures:
	 * - Measure.BRIX
	 * - Measure.DENSITY
	 * - Measure.ABV
	 * - Measure.CW
	 * 
	 * Other measurements can be derived from Liqueur.composition
	 * 
	 * @override
	 */
	get(measure) {
		switch (measure) {
			case Measure.DENSITY:
				return this.density;
				break;
			case Measure.ABV:
				return this.composition.info().abv;
				break;
			case Measure.BRIX:
				let info = this.composition.info();
				return info.sugar / info.weight * 100;
				break;
			case Measure.CW:
				let sugar = this.composition.component('sugar'),
					alcohol = this.composition.component('alcohol');
				let sugar_kcal = sugar ? sugar.get(Measure.CW) * sugar.get(Measure.G) * 0.001 / this.density : 0,
					alcohol_kcal = alcohol ? alcohol.get(Measure.CW) * alcohol.get(Measure.G) * 0.001 / this.density : 0;
				return 	sugar_kcal + alcohol_kcal;
				break;
		}
		return null;
	}
	/**
	 * Make a composition
	 *
	 * @param {MakeFrom} data
	 * @returns {Composition}
	 *
	 * @example
	 * let HomemadeCremeDeCassis = CremeDeCassis.make({
	 * 	alcohol: new Alcohol(0.4, Measure.WV)
	 * 	syrup: new Syrup(1, Measure.WV)
	 * })
	 */
	make(data) {
		data = data || {};
		data.fallback = data.fallback || {};
		data.basis = data.basis || { source: 'total', value: 1000, measure: Measure.ML };

		let composition = new Composition();

		if (!data.alcohol && data.fallback && data.fallback.alcohol) {
			data.alcohol = data.fallback.alcohol;
			data.fallback.alcohol = null;
		}

		if (!data.syrup && data.fallback && data.fallback.syrup) {
			data.syrup = data.fallback.syrup;
			data.fallback.syrup = null;
		}

		let c = this.composition;
		let goal = {
			sugar_content: c.component('sugar')
				? c.component('sugar').get(Measure.G)
				: 0,
			ethanol_content: c.component('alcohol')
				? c.component('alcohol').get(Measure.WW) * c.component('alcohol').get(Measure.G)
				: 0,
		};
		let weight = {
			syrup: data.syrup ? (goal.sugar_content / data.syrup.get(Measure.WW)) : 0,
			fallback_syrup: data.fallback.syrup ? (goal.sugar_content / data.fallback.syrup.get(Measure.WW)) : 0,
			alcohol: data.alcohol ? (goal.ethanol_content / data.alcohol.get(Measure.WW)) : 0,
			fallback_alcohol: data.fallback.alcohol ? (goal.ethanol_content / data.fallback.alcohol.get(Measure.WW)) : 0,
			total: this.density * 1000,
		}
		const EPS = weight.total * 1e-9;

		// validation
		if (goal.sugar_content > 0 && !weight.syrup) {
			throw new CalculationError('INSUFFICIENT_SUGAR');
		}
		if (goal.ethanol_content > 0 && !weight.alcohol) {
			throw new CalculationError('INSUFFICIENT_ALCOHOL');
		}

		let weight_result = {
			syrup: weight.syrup,
			fallback_syrup: 0,
			alcohol: weight.alcohol,
			fallback_alcohol: 0,
			total: weight.total,
		}
		let deficit = () => weight_result.syrup
			+ weight_result.fallback_syrup
			+ weight_result.alcohol
			+ weight_result.fallback_alcohol
			- weight.total;

		let buf = weight.total - weight.syrup - weight.alcohol, D = 0, x = 0;
		if (buf < 0) {
			D = deficit();
			buf = 0;
			if (data.priority && data.priority == 'syrup') {
				if (!weight.fallback_alcohol || weight.fallback_alcohol > weight.alcohol) {
					throw new CalculationError('INSUFFICIENT_ALCOHOL');
				}
				x = Math.min(1, D / (weight.alcohol - weight.fallback_alcohol));
				weight_result.alcohol = weight.alcohol * (1 - x);
				weight_result.fallback_alcohol = weight.fallback_alcohol * x;
				D = deficit();
				if (D > EPS) {
					if (!weight.fallback_syrup || weight.fallback_syrup > weight.syrup) {
						throw new CalculationError('INSUFFICIENT_SUGAR');
					}
					x = Math.min(1, D / (weight.syrup - weight.fallback_syrup));
					weight_result.syrup = weight.syrup * (1 - x);
					weight_result.fallback_syrup = weight.fallback_syrup * x;
					D = deficit();
				}
				if (D > EPS) {
					throw new CalculationError('IMPOSSIBLE_COMBINATION');
				}
			} else {
				if (goal.sugar_content > 0) {
					if (!weight.fallback_syrup || weight.fallback_syrup > weight.syrup) {
						throw new CalculationError('INSUFFICIENT_SUGAR');
					}
					x = Math.min(1, D / (weight.syrup - weight.fallback_syrup));
					weight_result.syrup = weight.syrup * (1 - x);
					weight_result.fallback_syrup = weight.fallback_syrup * x;
					D = deficit();
				}
				if (D > EPS && goal.ethanol_content > 0) {
					if (!weight.fallback_alcohol || weight.fallback_alcohol > weight.alcohol) {
						throw new CalculationError('INSUFFICIENT_ALCOHOL');
					}
					x = Math.min(1, D / (weight.alcohol - weight.fallback_alcohol));
					weight_result.alcohol = weight.alcohol * (1 - x);
					weight_result.fallback_alcohol = weight.fallback_alcohol * x;
					D = deficit();
				}
				if (D > EPS) {
					throw new CalculationError('IMPOSSIBLE_COMBINATION');
				}
			}
		}
		if (weight_result.syrup > 0) {
			composition.add('syrup', new Component(data.syrup, weight_result.syrup, Measure.G));
		}
		if (weight_result.fallback_syrup > 0) {
			composition.add('fallback_syrup', new Component(data.fallback.syrup, weight_result.fallback_syrup, Measure.G));
		}
		if (weight_result.alcohol > 0) {
			composition.add('alcohol', new Component(data.alcohol, weight_result.alcohol, Measure.G));
		}
		if (weight_result.fallback_alcohol > 0) {
			composition.add('fallback_alcohol', new Component(data.fallback.alcohol, weight_result.fallback_alcohol, Measure.G));
		}
		
		let volume_left = buf / Density.WATER;
		if (volume_left > EPS) {
			let buffer = data.buffer || new Water;
			composition.add(
				'buffer',
				new Component(
					buffer,
					volume_left,
					Measure.ML
				)
			);
		}

		let current = 0;
		switch (data.basis.source) {
			case 'alcohol':
                if (!composition.component('alcohol'))
                    throw new CalculationError('BASIS_ALCOHOL_WITHOUT_ALCOHOL');
				current = composition.component('alcohol').get(data.basis.measure);
				break;
			case 'syrup':
                if (!composition.component('syrup'))
                    throw new CalculationError('BASIS_SUGAR_WITHOUT_SUGAR');
				current = composition.component('syrup').get(data.basis.measure);
				break;
			default:
				current = composition.total(data.basis.measure);
				break;
		}
		let k = data.basis.value / current;
		
		composition.scale(k);

		return composition;
	}
}

/**
 * @typedef {Object} MakeFrom
 * @property {Alcohol} [alcohol] - main alcohol
 * @property {Syrup} [syrup] - main syrup/sugar
 * @property {('alcohol'|'syrup')} [priority='alcohol'] - priority in constructions
 * @property {Object} [basis] - calculation basis
 * @property {('alcohol'|'syrup'|'total')} basis.source
 * @property {number} basis.value - value
 * @property {MeasureVariant} basis.measure - Measure.*
 * @property {Object} [fallback] - fallback ingredients
 * @property {Alcohol} [fallback.alcohol] - fallback alcohol
 * @property {Syrup} [fallback.syrup] - fallback syrup/sugar
 */