package states

import (
	"fmt"
	"math/rand"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/inpututil"
	"src.robn.tv/MrDonuts/RGB/assets"
	geom "src.robn.tv/MrDonuts/RGB/geometry"
	score "src.robn.tv/MrDonuts/RGB/tools"
)

var CurrTrack = 1

type PlayLevelState struct {
}

func (s *PlayLevelState) Enter() {
	fmt.Println("Entering Play State")
	geom.SetupPlayer()
	fmt.Println(geom.GameGrid.ColouredSquaresRemaining())

}

func (s *PlayLevelState) Exit() {
	fmt.Println("Exiting Play State")

	geom.PrepareForNextLevel()

	if CurrTrack < len(assets.SongTracks) {
		if geom.CurrentLevel%3 == 0 {
			CurrTrack++
			assets.SongTracks[CurrTrack].SetVolume(0.7)
		}
	}

}

func (s *PlayLevelState) Update() {

	if inpututil.IsKeyJustPressed(ebiten.KeyN) {
		newRowSize := min(rand.Intn(5+geom.CurrentLevel)+2, geom.MaxGridDimension)
		newColSize := min(rand.Intn(5+geom.CurrentLevel)+2, geom.MaxGridDimension)
		geom.BuildGrid(newRowSize, newColSize)
		SM.Transition("load")
		assets.SFXLibrary["newLevel"].Rewind()
		assets.SFXLibrary["newLevel"].Play()
	}

	geom.MainPlayer.Update()
	if geom.CurrentEnergy == 0 {
		SM.Transition("game over")
	}
	if geom.GameGrid.ColouredSquaresRemaining() == 0 {
		//go to next level
		newRowSize := min(rand.Intn(5+geom.CurrentLevel)+2, geom.MaxGridDimension)
		newColSize := min(rand.Intn(5+geom.CurrentLevel)+2, geom.MaxGridDimension)
		geom.BuildGrid(newRowSize, newColSize)
		SM.Transition("load")
		assets.SFXLibrary["newLevel"].Rewind()
		assets.SFXLibrary["newLevel"].Play()
	}

}

func (s *PlayLevelState) Draw(screen *ebiten.Image) {
	geom.GameGrid.Draw(screen)
	geom.MainPlayer.Draw(screen)
	score.ScoreMngr.Draw(screen)
}
