package elements

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

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

type Boss struct {
	Sprite          *ebiten.Image
	Maks            *ebiten.Image
	MaskDest        *ebiten.Image
	Spawned         bool
	Pos             gamedata.Coordinates
	Right           bool
	Health          int
	Touched         bool
	damage          bool
	cycle           int
	Action          MoverAction
	hitcount        int
	damageduration  int
	SplodeInitiated bool
}

func NewBoss() *Boss {
	b := &Boss{
		Sprite:   ebiten.NewImage(96, 96),
		Spawned:  false,
		Action:   MoverActionDefault,
		hitcount: 0,
		Maks:     ebiten.NewImage(96, 96),
		MaskDest: ebiten.NewImage(96, 96),
		Health:   100,
		Touched:  false,
	}
	b.Maks.Fill(color.White)
	return b
}

func (b *Boss) Update() {
	if b.damage {
		b.damageduration++
		if b.damageduration > 30 {
			b.damage = false
			b.damageduration = 0
		}
	}
	if b.Action == MoverActionDead {
		b.Spawned = false
	}
	b.cycle++
}

func (b *Boss) Draw() {
	b.Sprite.Clear()
	b.MaskDest.Clear()

	/*
		//b.Sprite.Fill(color.RGBA{R: 0xFF, G: 0xFF, B: 0x00, A: 0xFF})
		vector.DrawFilledCircle(b.Sprite, 48, 48, 48, color.RGBA{R: 0xFF, G: 0xFF, B: 0x00, A: 0xFF}, true)
	*/

	idx := (b.cycle / 8) % 4
	x0 := 96 * idx
	x1 := x0 + 96
	y0 := 0
	y1 := 96

	op := &ebiten.DrawImageOptions{}
	if b.Right {
		op.GeoM.Scale(-1, 1)
		op.GeoM.Translate(MOVER_WIDTH*2, 0)
	}

	switch b.Action {
	case MoverActionDefault:
		b.Sprite.DrawImage(assets.ImageBank[assets.Worm].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)
	case MoverActionDamaged:
		if (b.cycle/5)%2 == 0 && b.damage {
			b.MaskDest.DrawImage(assets.ImageBank[assets.WormDamaged].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)
			op := &ebiten.DrawImageOptions{}
			op.GeoM.Reset()
			op.Blend = ebiten.BlendSourceAtop
			b.MaskDest.DrawImage(b.Maks, op)
			b.Sprite.DrawImage(b.MaskDest, nil)
		} else {
			b.Sprite.DrawImage(assets.ImageBank[assets.WormDamaged].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)
		}
	case MoverActionExploding:
		op.GeoM.Scale(2, 2)
		//op.GeoM.Translate(-48, -48)
		b.Sprite.DrawImage(assets.ImageBank[assets.FlyEyeDying].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)
		if idx == 3 {
			b.Action++
		}
	}

}

func (b *Boss) SetHit() {
	b.hitcount++
	b.damage = true
	b.Health--

	if b.Health <= 0 {
		b.Action = MoverActionExploding
		b.cycle = 0
	}
}

func (b *Boss) Reset() {
	b.hitcount = 0
	b.damage = false
	b.damageduration = 0
	b.Action = MoverActionDefault
	b.Spawned = false
	b.Health = 100
}

func (b *Boss) ToggleColor() {
	if b.Action == MoverActionDefault {
		b.Action = MoverActionDamaged
	} else if b.Action == MoverActionDamaged {
		b.Action = MoverActionDefault
	}
}
