// +build js,wasm

package main

import (
	"fmt"
	"image/jpeg"
	"math/rand"
	"net/http"
	"time"

	"git.kirsle.net/go/render"
	"git.kirsle.net/go/render/canvas"
)

// Config variables.
var (
	Filename = "photo.jpg"
	Width    = 640
	Height   = 480
	Quality  = 4

	// computed.
	Size = Width * Height
)

// Runtime variables.
var (
	app       *App
	mw        *canvas.Engine
	TargetFPS = 1000 / 60 // run at 60fps
)

func main() {
	setup()
	go mainloop()
	for {
		time.Sleep(10 * time.Second)
	}
}

// setup the applet
func setup() {
	var err error
	// Seed the random number generator.
	rand.Seed(time.Now().UnixNano())

	// Get the HTML Canvas.
	mw, err = canvas.New("canvas")
	if err != nil {
		panic(err)
	}

	// Configure the engine.
	err = mw.Setup()
	if err != nil {
		panic(err)
	}

	mw.AddEventListeners()

	// Fetch the image via HTTP.
	r, err := http.Get(Filename)
	if err != nil {
		panic(err)
	}

	// Parse it as a jpeg.
	photo, err := jpeg.Decode(r.Body)
	if err != nil {
		panic(err)
	}

	app = New(mw, photo)
}

// loop runs the applet logic for each loop.
func loop() bool {
	app.Ripple()

	fmt.Println("loop")

	mw.Clear(render.White)

	// Poll events.
	ev, err := mw.Poll()
	if err != nil {
		panic(err)
	}

	// Is mouse over the drawing?
	if ev.CursorX >= 0 && ev.CursorX < Width && ev.CursorY >= 0 && ev.CursorY < Width {
		app.Disturb(ev.CursorX, ev.CursorY, 15000)
	}

	// rain
	// app.Disturb(
	// 	int(math.Floor(rand.Float64()*float64(Width))),
	// 	int(math.Floor(rand.Float64()*float64(Height))),
	// 	int(rand.Float64()*10000),
	// )
	app.Present()

	// test
	for pt := range render.IterLine(render.Origin, render.NewPoint(128, 128)) {
		mw.DrawPoint(render.Black, pt)
	}
	return true
}

// mainloop runs a loop of loop() while maintaing the frame rate.
func mainloop() {
	var (
		start   time.Time
		elapsed time.Duration
		ok      bool
	)

	for {
		// Record how long the frame takes.
		start = time.Now()
		ok = loop()

		// Delay to maintain target frames per second.
		var delay uint32
		elapsed = time.Now().Sub(start) / time.Millisecond
		if TargetFPS-int(elapsed) > 0 {
			delay = uint32(TargetFPS - int(elapsed))
		}
		mw.Delay(delay)

		if !ok {
			break
		}
	}
}
