package main

import (
	"log"
	"runtime"

	"golang.org/x/mobile/app"
	"golang.org/x/mobile/event/lifecycle"
	"golang.org/x/mobile/event/paint"
	"golang.org/x/mobile/event/size"
//	"golang.org/x/mobile/geom"
	"golang.org/x/mobile/gl"
)

func main() {
	app.Main(func(a app.App) {
		var (
			glctx    gl.Context
			sz       size.Event
			// rotation geom.Angle
		)

		for e := range a.Events() {
			switch e := a.Filter(e).(type) {
			case lifecycle.Event:
				switch e.Crosses(lifecycle.StageVisible) {
				case lifecycle.CrossOn:
					glctx, _ = e.DrawContext.(gl.Context)
					onStart(glctx)
				case lifecycle.CrossOff:
					onStop()
					glctx = nil
				}
			case size.Event:
				sz = e
			case paint.Event:
				if glctx == nil {
					continue
				}
				onDraw(glctx, sz)
				a.Publish()
			}
		}
	})
}

func onStart(glctx gl.Context) {
	log.Println("jwc OPENGL App started")
	log.Println("jwc OPENGL App started")
	log.Println("jwc OPENGL App started")
	log.Println("jwc OPENGL App started")
	log.Println("jwc OPENGL App started")
	glctx.ClearColor(0.1, 0.5, 0.8, 0.5)
	glctx.Clear(gl.COLOR_BUFFER_BIT)
}

func onStop() {
	log.Println("App stopped")
}

func onDraw(glctx gl.Context, sz size.Event) {
	runtime.LockOSThread()

	glctx.ClearColor(0.1, 0.5, 0.8, 0.5)
	glctx.Clear(gl.COLOR_BUFFER_BIT)

	runtime.UnlockOSThread()
}
