package main

// import "os"
import "log"
import "fmt"
import "time"

import "github.com/davecgh/go-spew/spew"

import "git.wit.org/wit/gui"
import pb "git.wit.org/jcarr/witProtobuf"

import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"

var first *gui.GuiWindow
var config *pb.Config

// This sometimes crashes on the most recent window 
// under linux. but it doesn't always crash

func main() {
	config = pb.MakeDefaultConfig()
	// gui.Data.Config = c

	i := 1

	config.Width = int32(400 + 50 * i)
	config.Height = int32(400 + 50 * i)
	config.Hostname = fmt.Sprintf("splash %d", i)
	first = StartNewWindow(config, true, "SPLASH")

	i += 1
	config.Width = int32(400 + 50 * i)
	config.Hostname = fmt.Sprintf("splash %d", i)
	StartNewWindow(config, true, "BLAH")

	i += 1
	config.Width = int32(400 + 50 * i)
	config.Hostname = fmt.Sprintf("splash %d", i)
	StartNewWindow(config, false, "BLAH")

	for {
		i += 1
		config.Width = int32(400 + 50 * i)
		config.Hostname = fmt.Sprintf("splash %d", i)
		StartNewWindow(config, false, "SPLASH")

		i += 1
		config.Width = int32(400 + 50 * i)
		config.Hostname = fmt.Sprintf("splash %d", i)
		StartNewWindow(config, false, "BLAH")
	}
}

func StartNewWindow(c *pb.Config, bg bool, action string) *gui.GuiWindow {
	log.Println("InitNewWindow() Create a new window")

	var newGuiWindow *gui.GuiWindow
	newGuiWindow = new(gui.GuiWindow)
	// newGuiWindow.Config = c


	/*
	ui.OnShouldQuit(func() bool {
		// mouseClick(&newBM)
                ui.Quit()
		return true
	})
	*/

	time.Sleep(1000 * time.Millisecond)
	if (bg) {
		log.Println("ShowWindow() IN NEW GOROUTINE")
		go ui.Main(func() {
			InitWindow(newGuiWindow)
		})
		time.Sleep(2000 * time.Millisecond)
	} else {
		log.Println("ShowWindow() WAITING for ui.Main()")
		ui.Main(func() {
			InitWindow(newGuiWindow)
		})
	}
	return newGuiWindow
}

func InitWindow(gw *gui.GuiWindow) {
	log.Println("InitWindow() NEW WINDOW gw =", gw)

	c := config
	gw.UiWindow = ui.NewWindow("", int(c.Width), int(c.Height), true)
	// gw.UiWindow.SetBorderless(false)

	blah := gw
	gw.UiWindow.OnClosing(func(*ui.Window) bool {
		log.Println("InitWindow() OnClosing() blah")
		log.Println("InitWindow() OnClosing() blah")
		log.Println("InitWindow() OnClosing() blah")
		log.Println("InitWindow() OnClosing() blah")
		spew.Dump(blah)
		spew.Dump(gw)
		log.Println("InitWindow() OnClosing() THIS WINDOW IS CLOSING gw=", gw)
		spew.Dump(gw)
		spew.Dump(gw.UiWindow)
		// mouseClick(&newBM)
		if (gw.UiWindow != nil) {
			gw.UiWindow.Hide()
		}
		time.Sleep(1000 * time.Millisecond)
		spew.Dump(gw)
		// gw.UiWindow.Destroy()
                ui.Quit()
		time.Sleep(1000 * time.Millisecond)
		return true
	})

	// gw.UiWindow.SetChild(gw.T)
	// gw.UiWindow.SetMargined(true)

	log.Println("InitWindow() Show() gw.Name =", gw.Name)
	gw.UiWindow.Show()
}
