package elements

import (
	"image"
	"mover/assets"
	"mover/gamedata"

	_ "embed"
	"image/color"
	_ "image/png"

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

const (
	MOVER_WIDTH  = 48
	MOVER_HEIGHT = 48
)

const (
	HeroActionDefault = iota
	HeroActionDamaged
	HeroActionDying
	HeroActionExploding
	HeroActionDead
	HeroActionMax
)

type HeroAction uint

type Hero struct {
	Sprite     *ebiten.Image
	Maks       *ebiten.Image
	MaksDest   *ebiten.Image
	Angle      float64
	Pos        gamedata.Coordinates
	Origin     gamedata.Coordinates
	Lastpos    gamedata.Coordinates
	Action     HeroAction
	cycles     int
	Upgrade    bool
	rotating   bool
	Toggled    bool
	Hit        bool
	Touched    bool
	Left       bool
	dyingcount int
}

func NewHero() *Hero {
	m := &Hero{
		Sprite:     ebiten.NewImage(MOVER_WIDTH, MOVER_HEIGHT),
		Maks:       ebiten.NewImage(MOVER_WIDTH, MOVER_HEIGHT),
		MaksDest:   ebiten.NewImage(MOVER_WIDTH, MOVER_HEIGHT),
		Action:     HeroActionDefault,
		cycles:     4,
		Angle:      0,
		rotating:   false,
		Toggled:    false,
		dyingcount: 0,
		Upgrade:    true,
	}

	m.Maks.Fill(color.White)
	return m
}

func (m *Hero) ToggleRotate() {
	m.rotating = !m.rotating
}

func (m *Hero) SetAngle(a float64) {
	m.Angle = a
}

func (m *Hero) SetOrigin(coords gamedata.Coordinates) {
	m.Origin = coords
	m.Pos = coords
}

func (m *Hero) Draw() {
	m.Sprite.Clear()
	m.MaksDest.Clear()

	idx := (m.cycles / 8) % 4

	y0 := 0
	y1 := 48
	x0 := 48 * idx
	x1 := x0 + 48

	op := &ebiten.DrawImageOptions{}
	if m.Left {
		op.GeoM.Scale(-1, 1)
		op.GeoM.Translate(MOVER_WIDTH, 0)
	}

	switch m.Action {
	case HeroActionDefault:
		m.Sprite.DrawImage(assets.ImageBank[assets.HeroNormal].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)
	case HeroActionDying:
		m.Sprite.DrawImage(assets.ImageBank[assets.HeroDying].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)

		if m.dyingcount >= 31 {
			m.cycles = 0
			m.Action++
		}
	case HeroActionExploding:
		m.Sprite.DrawImage(assets.ImageBank[assets.HeroDying].SubImage(image.Rect(48*3, 0, 48*4, 48)).(*ebiten.Image), op)
	default:
	}
}

func (m *Hero) Update() {

	if m.Action == HeroActionDying {
		m.dyingcount++
	}
	m.cycles++
}

// one hit death for the hero
func (m *Hero) SetHit() {
	m.Action = HeroActionDying
	m.dyingcount = 0
	m.Angle = 0
	m.cycles = 0
}

func (m *Hero) ToggleColor() {
	//m.Toggled = !m.Toggled
	if m.Action == HeroActionDefault {
		m.Action = HeroActionDamaged
	} else if m.Action == HeroActionDamaged {
		m.Action = HeroActionDefault
	}
}
