package main

import (
	"embed"
	"fmt"
	_ "image/jpeg"
	"io"
	"io/fs"
	"log"
	"os"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/audio/mp3"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
)

var (
	// TODO: Make this redundant
	//go:embed src/frames/output_*.jpg
	assetsFS embed.FS

	sampleRate = 44100
	bps        = 32
	brate      = 128
)

type Game struct {
	count        int
	frame        *ebiten.Image
	files        []fs.DirEntry
	audioContext *audio.Context
	player       *audio.Player
	started      bool
}

func (g *Game) Update() error {

	var err error

	g.frame, _, err = ebitenutil.NewImageFromFile("src/frames/" + g.files[g.count].Name())
	if err != nil {
		log.Fatal(err)
	}

	ebitenutil.DebugPrint(g.frame, "src/frames/"+g.files[g.count].Name())

	// Up by one
	if g.count != 6571 {
		g.count++
	} else {
		return ebiten.Termination
	}

	// Play Audio
	if !g.started {
		g.player.SetVolume(0.7)
		g.player.Play()
		g.started = true
	}

	return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
	op := &ebiten.DrawImageOptions{}
	screen.DrawImage(g.frame, op)
}

func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
	return 480, 360
}

func main() {

	files, err := assetsFS.ReadDir("src/frames")
	if err != nil {
		fmt.Println("Error reading embedded directory:", err)
		return
	}

	// Do all the audio things. This isn't working...
	// Create audio context
	ctx := audio.NewContext(sampleRate)

	// Open MP3 file
	f, err := os.Open("src/bad-apple-audio.mp3")
	if err != nil {
		log.Fatal(err)
	}
	//defer f.Close()

	// Decode MP3
	stream, err := mp3.DecodeWithSampleRate(sampleRate, f)
	if err != nil {
		log.Fatal(err)
	}

	// Create player
	player, err := audio.NewPlayer(ctx, io.NopCloser(stream))
	if err != nil {
		log.Fatal(err)
	}

	ebiten.SetWindowSize(640, 480)
	ebiten.SetWindowTitle("Ebitengine: Bad Apple")

	game := &Game{
		count:        0,
		files:        files,
		player:       player,
		audioContext: ctx,
	}

	// Ensure that the image doesn't go twice as fast as it should've.
	ebiten.SetTPS(30)

	// Play the thing
	if err := ebiten.RunGame(game); err != nil {
		panic(err)
	}

	fmt.Println("Now go to bed, you are tired...")

}
