import { loadGltf } from './loadgltf.js'
import gsap from 'gsap'
import * as THREE from 'three'

export default class Ingredient {
    constructor(ingredientInfo, game) {
        this.ingredientInfo = ingredientInfo
        this.model = null
        this.game = game
    }

    getName() {
        return this.ingredientInfo.name
    }

    async spawn(shelfSlot, stageData) {
        this.model = await loadGltf(this.game, this.ingredientInfo.model)
        this.shelfSlot = shelfSlot
        this.model.position.x = shelfSlot.position.x
        this.model.position.y = shelfSlot.position.y
        this.model.position.z = shelfSlot.position.z

        this.game.scene.add(this.model)
        return this.model
    }
    beginBrew() {
        this.model.moving = true
        clearTimeout(this.model.timeoutId)
        gsap.to(this.model.scale, {
            duration: 2.5, x: 0, y: 0, z: 0, onComplete: () => {
    
                this.model.visible = false
                this.model.timeoutId = setTimeout(() => {
                    this.model.position.x = this.shelfSlot.position.x
                    this.model.position.y = this.ingredientInfo.wobble.amplitude * Math.sin(this.ingredientInfo.wobble.frequency * this.game.clock.getElapsedTime() + 700) + (this.shelfSlot.position.y + this.ingredientInfo.shelfOffset)
                    this.model.position.z = this.shelfSlot.position.z
                    this.model.visible = true
                    gsap.to(this.model.scale, {
                        duration: 0.7, x: 1, y: 1, z: 1, ease: "bounce", onComplete: () => {
                            this.model.moving = false
                        }
                    })
                }, 3000)
            }
        })
        gsap.to(this.model.position, {
            duration: 1.5, motionPath: this.shelfSlot.motionPath, onComplete: () => {

            }
        })
    }

    wobble() {
        if (!this.model.moving) {
            this.model.position.y = this.ingredientInfo.wobble.amplitude * Math.sin( this.ingredientInfo.wobble.frequency * this.game.clock.getElapsedTime()) + (this.shelfSlot.position.y + this.ingredientInfo.shelfOffset)
            this.model.rotateOnAxis(new THREE.Vector3(0, 1, 0), - this.ingredientInfo.wobble.rotation)
        }
    }
}