package scenario

import (
	"image"
	"sort"

	"github.com/hajimehoshi/ebiten"
)

func (s *Scenario) Update(screenX, screenY int) error {
	s.tick += 1

	return nil
}

func (s *Scenario) Draw(screen *ebiten.Image) error {
	// Bounds clipping
	// http://www.java-gaming.org/index.php?topic=24922.0
	// https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds
	// https://gamedev.stackexchange.com/questions/25896/how-do-i-find-which-isometric-tiles-are-inside-the-cameras-current-view

	sw, sh := screen.Size()

	topLeft := pixToCell(s.Viewpoint)
	topLeft.X -= 5 // Ensure we paint to every visible section of the screeen.
	topLeft.X -= 5 // FIXME: haxxx

	bottomRight := pixToCell(image.Pt(s.Viewpoint.X+sw, s.Viewpoint.Y+sh))
	bottomRight.X += 5
	bottomRight.Y += 5

	// X+Y is constant for all tiles in a column
	// X-Y is constant for all tiles in a row
	// However, the drawing order is odd unless we reorder explicitly.
	toDraw := []image.Point{}
	for a := topLeft.X + topLeft.Y; a <= bottomRight.X+bottomRight.Y; a++ {
		for b := topLeft.X - topLeft.Y; b <= bottomRight.X-bottomRight.Y; b++ {
			if b&1 != a&1 {
				continue
			}

			pt := image.Pt((a+b)/2, (a-b)/2)

			if !pt.In(s.area.Rect) {
				continue
			}
			toDraw = append(toDraw, pt)
		}
	}

	sort.Slice(toDraw, func(i, j int) bool {
		iPix := cellToPix(toDraw[i])
		jPix := cellToPix(toDraw[j])

		if iPix.Y < jPix.Y {
			return true
		}

		if iPix.Y == jPix.Y {
			return iPix.X < jPix.X
		}

		return false
	})

	counter := map[string]int{}
	for _, pt := range toDraw {
		for z := 0; z <= s.ZIdx; z++ {
			if err := s.renderCell(pt.X, pt.Y, z, screen, counter); err != nil {
				return err
			}
		}
	}

	//log.Printf("%#+v", counter)

	return nil
}

func (s *Scenario) renderCell(x, y, z int, screen *ebiten.Image, counter map[string]int) error {
	sprites, err := s.area.SpritesForCell(x, y, z)
	if err != nil {
		return err
	}

	iso := ebiten.GeoM{}
	iso.Translate(-float64(s.Viewpoint.X), -float64(s.Viewpoint.Y))

	pix := cellToPix(image.Pt(x, y))
	iso.Translate(float64(pix.X), float64(pix.Y))

	// Taking the Z index away *seems* to draw the object in the correct place.
	// FIXME: There are some artifacts, investigate more
	iso.Translate(0.0, -float64(z*48.0)) // offset for Z index

	// TODO: iso.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor

	for _, spr := range sprites {
		//		if _, ok := counter[spr.ID]; !ok {
		//			counter[spr.ID] = 0
		//		}
		//		counter[spr.ID] = counter[spr.ID] + 1

		iso.Translate(float64(spr.XOffset), float64(spr.YOffset))

		if err := screen.DrawImage(spr.Image, &ebiten.DrawImageOptions{GeoM: iso}); err != nil {
			return err
		}
		iso.Translate(float64(-spr.XOffset), float64(-spr.YOffset))
	}

	return nil
}

const (
	cellWidth  = 64
	cellHeight = 64
)

// Doesn't take the camera or Z level into account
func cellToPix(pt image.Point) image.Point {
	return image.Pt(
		(pt.X-pt.Y)*cellWidth,
		(pt.X+pt.Y)*cellHeight/2,
	)
}

// Doesn't take the camera or Z level into account
func pixToCell(pt image.Point) image.Point {
	return image.Pt(
		pt.Y/cellHeight+pt.X/(cellWidth*2),
		pt.Y/cellHeight-pt.X/(cellWidth*2),
	)
}
