package screens

import (
	"image/color"
	"math"
	"mover/assets"
	"mover/fonts"
	"mover/gamedata"
	"mover/touch"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/inpututil"
	"github.com/hajimehoshi/ebiten/v2/text"
)

type StartScreen struct {
	eHandler      map[ScreenManagerEvent]func()
	dimensions    gamedata.Area
	target        gamedata.Coordinates
	current       gamedata.Coordinates
	targetreached bool
	audioplayed   bool
	cycle         int
	audioplayer   *audio.Player
}

func NewStartScreen() *StartScreen {
	s := &StartScreen{
		eHandler:      make(map[ScreenManagerEvent]func()),
		target:        gamedata.Coordinates{X: 640/2 - 150, Y: 480 / 2},
		current:       gamedata.Coordinates{X: 640/2 - 150, Y: -100},
		targetreached: false,
		cycle:         0,
		audioplayed:   false,
	}
	return s
}

func (s *StartScreen) Update() error {

	touch.UpdateTouchIDs()

	ids := touch.GetTouchIDs()
	var touched bool = false
	for _, id := range ids {
		touched = touch.IsTouchJustPressed(id)
		if touched {
			break
		}
	}

	if inpututil.IsKeyJustPressed(ebiten.KeyEnter) ||
		ebiten.IsStandardGamepadButtonPressed(0, ebiten.StandardGamepadButtonCenterRight) ||
		touched {
		s.eHandler[EventCompleted]()
		if s.audioplayer.IsPlaying() {
			s.audioplayer.Close()
		}
	}

	if !s.audioplayed {
		s.audioplayer = audioContext.NewPlayerFromBytes(assets.Survive)
		s.audioplayer.Play()
		s.audioplayed = true
	}

	if !s.targetreached {
		s.current.X += (s.target.X - s.current.X) / 8
		s.current.Y += (s.target.Y - s.current.Y) / 8
	} else {
		s.current.Y += 0.5 * math.Sin(float64(s.cycle)/(math.Pi*8))
	}

	if math.Abs(s.current.Y-s.target.Y) < 1 && !s.targetreached {
		s.targetreached = true
	}

	s.cycle++
	return nil
}

func (s *StartScreen) Draw(screen *ebiten.Image) {
	screen.Clear()
	screen.DrawImage(assets.ImageBank[assets.Title], nil)
	text.Draw(screen, "survive", fonts.SurviveFont.ArcadeLarge, int(s.current.X), int(s.current.Y), color.Black)

	if s.targetreached && (s.cycle/16)%4 < 2 {
		text.Draw(screen, "press start", fonts.SurviveFont.Arcade, 640/2-25, 300, color.Black)
	}

	text.Draw(screen, "©bsoft games", fonts.SurviveFont.ArcadeSmall, 640/2+25, 180, color.Black)

}

func (s *StartScreen) SetEventHandler(e ScreenManagerEvent, f func()) {
	s.eHandler[e] = f
}

func (s *StartScreen) SetDimensions(a gamedata.Area) {
	s.dimensions = a
}
