import dispatch_default from "../../../d3-dispatch/src/dispatch.js";
import { timer } from "../../../d3-timer/src/timer.js";
import timeout_default from "../../../d3-timer/src/timeout.js";
var emptyOn = dispatch_default("start", "end", "cancel", "interrupt"), emptyTween = [], STARTING = 2, ENDING = 5, ENDED = 6;
function schedule_default(e, t, n, a, o, s) {
	var c = e.__transition;
	if (!c) e.__transition = {};
	else if (n in c) return;
	create(e, n, {
		name: t,
		index: a,
		group: o,
		on: emptyOn,
		tween: emptyTween,
		time: s.time,
		delay: s.delay,
		duration: s.duration,
		ease: s.ease,
		timer: null,
		state: 0
	});
}
function init(e, t) {
	var n = get(e, t);
	if (n.state > 0) throw Error("too late; already scheduled");
	return n;
}
function set(e, t) {
	var n = get(e, t);
	if (n.state > 3) throw Error("too late; already running");
	return n;
}
function get(e, t) {
	var n = e.__transition;
	if (!n || !(n = n[t])) throw Error("transition not found");
	return n;
}
function create(e, r, i) {
	var a = e.__transition, o;
	a[r] = i, i.timer = timer(s, 0, i.time);
	function s(e) {
		i.state = 1, i.timer.restart(c, i.delay, i.time), i.delay <= e && c(e - i.delay);
	}
	function c(t) {
		var s, d, f, p;
		if (i.state !== 1) return u();
		for (s in a) if (p = a[s], p.name === i.name) {
			if (p.state === 3) return timeout_default(c);
			p.state === 4 ? (p.state = 6, p.timer.stop(), p.on.call("interrupt", e, e.__data__, p.index, p.group), delete a[s]) : +s < r && (p.state = 6, p.timer.stop(), p.on.call("cancel", e, e.__data__, p.index, p.group), delete a[s]);
		}
		if (timeout_default(function() {
			i.state === 3 && (i.state = 4, i.timer.restart(l, i.delay, i.time), l(t));
		}), i.state = 2, i.on.call("start", e, e.__data__, i.index, i.group), i.state === 2) {
			for (i.state = 3, o = Array(f = i.tween.length), s = 0, d = -1; s < f; ++s) (p = i.tween[s].value.call(e, e.__data__, i.index, i.group)) && (o[++d] = p);
			o.length = d + 1;
		}
	}
	function l(t) {
		for (var n = t < i.duration ? i.ease.call(null, t / i.duration) : (i.timer.restart(u), i.state = 5, 1), r = -1, a = o.length; ++r < a;) o[r].call(e, n);
		i.state === 5 && (i.on.call("end", e, e.__data__, i.index, i.group), u());
	}
	function u() {
		for (var t in i.state = 6, i.timer.stop(), delete a[r], a) return;
		delete e.__transition;
	}
}
export { ENDED, ENDING, STARTING, schedule_default as default, get, init, set };
