import Big from 'big.js';
import { setState } from './store';

export function c(e) {
	e.preventDefault();
	history.pushState({}, null, e.target.href);
	setState('path', location.pathname.substring(1));
}

export function Null(props) {
	return props.children;
}
export function pgRange2String(s, type, min_p, max_p) {
	let n = [...new Set(s.slice(1, -1).split(','))];
	if(type === 'flower' || type === 'preroll'  || type === 'disposable' || type === 'cartridge') {
		return `${n.join(' - ')} % by mass`;
	} else if(type === 'oil') {
		return `${n.join(' - ')} mg / ml`;
	} else if(type === 'spray') {
		return `${n.join(' - ')} mg / spray(0.1ml)`
	} else if(type === 'capsule') {
		return `${n.join(' - ')} mg / capsule`;
	} else if(type === 'powder' || type === 'rtd' || type === 'shot') {
		return `${n.join(' - ')} mg`;
	} else if(max_p === undefined) {
		return `${n.join(' - ')} mg / pack, ${n.map(c => (new Big(c).div(min_p).toString())).join(' - ')} mg / ${type === 'tea' ? 'bag' : 'piece'}`;
	} else {
		let b = new Big(n[0]);
		return `${n[0]} mg / pack, ${b.div(max_p).toString()}${min_p === max_p ? '' : ' - ' + b.div(min_p).toString()} mg / ${type === 'tea' ? 'bag' : 'piece'}`;
	}
}
export function s(type) {
	let suffix = ' mg / ';
	if(type === 'flower' || type === 'preroll'  || type === 'disposable' || type === 'cartridge') {
		suffix = " % by mass";
	} else if(type === 'oil') {
		suffix += 'ml';
	} else if(type === 'spray') {//is it easier to input mg / ml or mg / bottle instead?
		suffix += 'spray(0.1ml)'
	} else if(type === 'capsule') {
		suffix += 'capsule';
	} else {
		suffix += 'pack';
	}
	return suffix;
}
export function ss(type) {
	if(type === 'oil' || type === 'spray') {
		return 'ml';
	} else if(type === 'capsule') {
		return 'mg';
	} else {
		return 'g';
	}
}
export function moneyRange(min, max) {
	if(min === max) {
		return `$${min}`;
	} else {
		return `$${min} - ${max}`;
	}
}
export function fmt(producer, brand, name) {
	if(producer === null) {
		return brand + ' ' + name;
	} else if(brand === '') {
		return producer + ' ' + name;
	} else {
		return `${brand} ${name} by ${producer}`;
	}
}
export function poop(type, portions, quantity, flavor) {
	let p = '';
	switch(type) {
		case 'preroll':
		case 'capsule':
			p = type;
			break;
		case 'tea':
			p = 'bag';
			break;
		case 'gummy':
		case 'mint':
		case 'chocolate':
		case 'baked':
			p = 'piece';
			break;
	}
	if(p.length) {
		p = portions + ' ' + p;
		if(portions > 1) {
			p += 's';
		}
		if(quantity) {
			p += ' X ';
		}
	}
	return `${p}${quantity ? quantity + ss(type) : ''}${flavor ? `(${flavor})` : ''}`;
}
export function create_deferred() {
	let resolve, reject;
	let p = new Promise((_resolve, _reject) => {resolve = _resolve; reject = _reject});
	p.resolve = resolve;
	p.reject = reject;
	return p;
}