package geom

import (
	"image/color"

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

var MainPlayer *Player
var totalColors = 3
var colorMap = map[int]color.Color{
	0: RedFill,
	1: GreenFill,
	2: BlueFill,
}
var defaultStartingEnergy = 50
var nextLevelEnergyJump = 30
var CurrentEnergy = defaultStartingEnergy
var CurrentLevel = 1

type Player struct {
	square         Square
	row            int
	col            int
	currColorIndex int
}

func SetupPlayer() {
	rows, _ := GameGrid.Size()

	//build default square
	sq := MakeSquare(GameGrid.squareSize)

	//adjust to red as starting value
	sq.ChangeColour(RedFill)

	//position on bottom left
	gridSq := GameGrid.GetSquareAt(rows, 1)
	sq.SetPosition(gridSq.x, gridSq.y)

	//setup struct for passing around
	ply := Player{square: sq, row: rows, col: 1, currColorIndex: 0}
	MainPlayer = &ply
}

func (p *Player) Update() {

	moveOccurs := false

	if inpututil.IsKeyJustPressed(ebiten.KeyArrowDown) {
		rows, _ := GameGrid.Size()
		if p.row < rows {
			p.row += 1
			p.square.moveDownOnGrid()
			moveOccurs = true
		}

	}

	if inpututil.IsKeyJustPressed(ebiten.KeyArrowRight) {
		_, cols := GameGrid.Size()
		if p.col < cols {
			p.col += 1
			p.square.moveRightOnGrid()
			moveOccurs = true
		}

	}

	if inpututil.IsKeyJustPressed(ebiten.KeyArrowLeft) {
		if p.col > 1 {
			p.col -= 1
			p.square.moveLeftOnGrid()
			moveOccurs = true
		}
	}

	if inpututil.IsKeyJustPressed(ebiten.KeyArrowUp) {
		if p.row > 1 {
			p.row -= 1
			p.square.moveUpOnGrid()
			moveOccurs = true
		}
	}

	if moveOccurs {
		moveOccurs = false

		p.NextColor()

		// check if player is on same colour square
		gridSquare := GameGrid.GetSquareAt(p.row, p.col)
		if p.currColorIndex == gridSquare.RGBColourIndex {
			GameGrid.coloredSquaresRemaining -= 1
			gridSquare.RGBColourIndex = -1
			gridSquare.ChangeColour(GrayFill)
			if GameGrid.coloredSquaresRemaining != 0 {
				assets.SFXLibrary["colourMatch"].Rewind()
				assets.SFXLibrary["colourMatch"].Play()
			}

		}

		// reduce energy
		CurrentEnergy -= 1
	}

}

func (p *Player) Draw(screen *ebiten.Image) {
	opts := &ebiten.DrawImageOptions{}
	opts.GeoM.Translate(float64(p.square.x), float64(p.square.y))
	screen.DrawImage(p.square.Img, opts)
}

func (p *Player) NextColor() {
	p.currColorIndex = (p.currColorIndex + 1) % totalColors
	p.square.ChangeColour(colorMap[p.currColorIndex])
}

func ResetPlayerValues() {
	CurrentEnergy = defaultStartingEnergy
	CurrentLevel = 1
}

func PrepareForNextLevel() {
	CurrentEnergy += nextLevelEnergyJump
	CurrentLevel += 1
}
