package main

import (
	"math"
	"math/rand"
	"time"

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

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

	// computed.
	Size = Width * Height
)

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

func main() {
	setup()
	mainloop()
}

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

	// Create SDL2 window.
	mw = sdl.New("Ripple effect", Width, Height)
	if err := mw.Setup(); err != nil {
		panic(err)
	}

	// Load the jpeg image.
	var err error
	photo, err := render.OpenImage(Filename)
	if err != nil {
		panic(err)
	}

	app = New(mw, photo)
}

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

	mw.Clear(render.White)

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

	// Escape key closes the program.
	if ev.Escape {
		mw.Teardown()
		return false
	}

	// 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()
	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
		}
	}
}
