package elements

import (
	"math"
	"mover/assets"
	"mover/gamedata"

	"github.com/hajimehoshi/ebiten/v2"
)

const (
	SPLASH_DIM          = 128
	SPLASH_ELEMS        = 10
	SPLASH_PRIMARY_SIZE = 46
)

type Splash struct {
	Sprite   *ebiten.Image
	position gamedata.Coordinates
	cycle    int
	opacity  float32
}

func NewSplash() *Splash {
	sp := &Splash{
		Sprite:  ebiten.NewImage(SPLASH_DIM, SPLASH_DIM),
		cycle:   0,
		opacity: 1,
	}
	return sp
}

func (sp *Splash) Update() error {
	sp.cycle++

	sp.opacity = sp.opacity - float32(sp.cycle)/(60*60)

	return nil
}

func (sp *Splash) Draw() {
	sp.Sprite.Clear()

	/*
		for i := SPLASH_ELEMS; i > 0; i-- {

			percent := float64(i) / SPLASH_ELEMS

			dx := 1 / percent * math.Cos(float64(sp.cycle)/(math.Pi*2))
			dy := -float64(i - SPLASH_ELEMS) //math.Sin(float64(sp.cycle) / (math.Pi * 2))

			op := &ebiten.DrawImageOptions{}
			op.GeoM.Translate(-SPLASH_DIM/2, -SPLASH_DIM/2)
			op.GeoM.Scale(percent, percent)
			//op.GeoM.Rotate(-(float64(sp.cycle - i*30)) / (math.Pi * 2))
			op.GeoM.Translate(SPLASH_DIM/2+dx, SPLASH_DIM/2+dy)
			//op.ColorScale.ScaleAlpha(float32(percent))
			sp.Sprite.DrawImage(assets.ImageBank[assets.Splash], op)
		}*/

	for i := 0; i < SPLASH_ELEMS; i++ {

		percent := float64(SPLASH_ELEMS-i) / SPLASH_ELEMS

		dy := -float64(i)*4 - float64(sp.cycle)/60
		dx := 2 / percent * math.Cos(float64(sp.cycle-i*10)/(math.Pi*2))

		op := &ebiten.DrawImageOptions{}
		op.GeoM.Translate(-48/2, -48/2)
		op.GeoM.Scale(percent, percent)
		op.GeoM.Rotate(-float64(sp.cycle) / (math.Pi * 4))
		op.GeoM.Translate(SPLASH_DIM/2, SPLASH_DIM/2)
		op.GeoM.Translate(dx, dy)

		op.ColorScale.ScaleAlpha(sp.opacity)

		sp.Sprite.DrawImage(assets.ImageBank[assets.Splash], op)
	}

	for i := 0; i < 5; i++ {

		percent := float64(5-i) / 5

		a := 9.8
		time := float64(sp.cycle) / 8
		v0 := 10.
		dy := 1/2.*a*math.Pow(time-float64(i), 2) - v0*time
		dx := -float64(sp.cycle)

		op := &ebiten.DrawImageOptions{}
		op.GeoM.Translate(-48/2, -48/2)
		op.GeoM.Scale(percent, percent)
		op.GeoM.Rotate(-float64(sp.cycle) / (math.Pi * 4))
		op.GeoM.Translate(SPLASH_DIM/2, SPLASH_DIM/2)
		op.GeoM.Translate(dx, dy)
		sp.Sprite.DrawImage(assets.ImageBank[assets.Splash], op)
		op.GeoM.Translate(-2*dx, 0)
		sp.Sprite.DrawImage(assets.ImageBank[assets.Splash], op)
	}
}

func (sp *Splash) GetPosition() gamedata.Coordinates {
	return sp.position
}

func (sp *Splash) SetPosition(pos gamedata.Coordinates) {
	sp.position = pos
}

func (sp *Splash) GetAlpha() float32 {
	return sp.opacity
}
