import Easing from "./Easings"
import * as RE from 'rogue-engine';

export class TweenManager {
	activeTweens = []
	elapsed = 0
	awake() {

	}
	start() {
		this.elapsed = 0

	}
	update() {
		this.elapsed += RE.Runtime.deltaTime
		let tweensToRemove = []
		this.activeTweens.forEach(tween => {
			if(tween.update(this.elapsed)) {
				tweensToRemove.push(tween)
			}
		})

		for(let i = tweensToRemove.length - 1; i >= 0; i--) {
			this.remove(tweensToRemove[i])
		}
	}

	add(simpleTween) {
		this.activeTweens.push(simpleTween)
		simpleTween.start(this.elapsed)
	}

	remove(simpleTween) {
		delete this.activeTweens[this.activeTweens.indexOf(simpleTween)]
	}
}

export class SimpleTween {
	constructor(initialObject, targetProperties, duration = 1000, easingFunction = Easing.Linear.EaseNone, onComplete = () => {}) {
		this.initialObject = initialObject
		this.targetProperties = targetProperties
		this.duration = duration / 1000
		this.easingFunction = easingFunction
		this.onComplete = onComplete
	}

	start(elapsed) {
		this.copy = {}
		for(let key in this.targetProperties) {
			this.copy[key] = this.initialObject[key]
		}
		this.begin = elapsed
	}

	update(elapsed) {
		if(elapsed >= this.begin + this.duration) {
			for(let key in this.targetProperties) {
				this.initialObject[key] = this.targetProperties[key]
			}
			this.onComplete()
			return true
		}

		let delta = (elapsed - this.begin) / this.duration
		for(let key in this.targetProperties) {
			this.initialObject[key] = (this.targetProperties[key] - this.copy[key]) * this.easingFunction(delta) + this.copy[key]
		}
		return false
	}
}
