package main

import "log"
// import "fmt"
import "time"
import "runtime"
import "os/exec"
import "strings"

import "git.wit.com/wit/gui"
import "git.wit.com/wit/shell"
// import pb "git.wit.com/wit/witProtobuf"

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

// import pb "git.wit.com/wit/witProtobuf"

func debugClick(b *gui.GuiButton) {
	log.Println("debugClick() START")
	gw := b.Box.Window

	box := gui.InitWindow(gw, "Debugging", gui.Yaxis)
	if (box == nil) { return }
	gw = box.Window
	log.Println("debugClick() InitWindow() END")

	makeButton(box, nil, nil, "empty", "SUBDOMAIN", nil)
	gui.HorizontalBreak(box)
	makeButton(box, nil, nil, "Create Subdomain Account", "ADD", addSubdomainClick)

	hardXbox := gui.HardBox(box.Window, gui.Xaxis, "subdomain test")
	Ybox1 := gui.NewBox(hardXbox, gui.Yaxis, "subdomain Y test")
	Xbox1 := gui.NewBox(Ybox1, gui.Xaxis, "subdomain Y test")
	makeButton(Xbox1, nil, nil, "ping", "SUBDOMAIN", runPingClick)
	makeButton(Xbox1, nil, nil, "Cross platform shell test", "SUBDOMAIN", runTestExecClick)
	makeButton(Xbox1, nil, nil, "empty 3", "SUBDOMAIN", nil)
	makeButton(Xbox1, nil, nil, "empty 4", "SUBDOMAIN", nil)

	Xbox1 = gui.NewBox(Ybox1, gui.Xaxis, "subdomain Y1 test")
	makeButton(Xbox1, nil, nil, "List all windows & tabs", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("gui.DumpBoxes()")
		gui.DumpBoxes()
	})
	makeButton(Xbox1, nil, nil, "Debug IPv6", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("Need to add IPv6 debugging here")
	})
	Ybox3 := gui.NewBox(Ybox1, gui.Yaxis, "subdomain Y1 test")
	gui.NewLabel(Ybox3, "git rev-list: " + config.Gitref)
	gui.NewLabel(Ybox3, "go build version: " + config.Goversion)
	gui.NewLabel(Ybox3, "build date: " + shell.Chomp(config.Builddate))

	Ybox2 := gui.NewBox(hardXbox, gui.Yaxis, "subdomain Y test")
	makeColorButton(Ybox2, nil, nil, "COLOR73", "COLOR73", nil)
	makeButton(Ybox2, nil, nil, "Hide all tabs", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("debugClick() Hide()")
		box := gw.BoxMap["MAINBOX"]
		box.Window.UiTab.Hide()
	})
	makeButton(Ybox2, nil, nil, "Hide sleep Show", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("debugClick() Hide()")
		box := gw.BoxMap["MAINBOX"]
		box.Window.UiTab.Hide()
		time.Sleep(2000 * time.Millisecond)
		box.Window.UiTab.Show()
	})
	/*
	makeButton(Ybox2, nil, nil, "Destroy tab 0", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("debugClick() Destroy(0)")
		box := gw.BoxMap["MAINBOX"]
		box.Window.UiTab.Delete(0)
	})
	*/
	makeButton(Ybox2, nil, nil, "Destroy Splash", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("debugClick() Destroy(0)")
		gui.DeleteWindow("Splash")
	})
	makeButton(Ybox2, nil, nil, "Destroy Debugging Tab", "SUBDOMAIN", func (*gui.GuiButton) {
		gui.DeleteWindow("Debugging")
	})

	makeButton(Ybox2, nil, nil, "Load the default test config file", "SUBDOMAIN", func (*gui.GuiButton) {
		newConfig := loadDefaultConfig()
		config.Accounts = newConfig.Accounts
	})
	makeButton(Ybox2, nil, nil, "runtime.Stack() dump", "SUBDOMAIN", func (*gui.GuiButton) {
		log.Println("\tATTEMPT FULL STACK DUMP")
		buf := make([]byte, 1<<16)
		runtime.Stack(buf, true)
		log.Printf("%s", buf)
		log.Println("\tFINISHED FULL STACK DUMP")
	})
	makeButton(Ybox2, nil, nil, "Close the GUI", "SUBDOMAIN", nil)
}

func runPingClick(b *gui.GuiButton) {
	log.Println("runPingClick START")
	values, _ := b.Values.(*myButtonInfo)
	log.Println("runTestExecClick values.VM", values.VM)
	hostname := "localhost"
	if (values.VM != nil) {
		hostname = values.VM.Hostname
	}
	spew.Dump(b)
	var tmp []string
	tmp = append(tmp, "nohup", "xterm", "-geometry", "120x30", "-e", "ping " + hostname + ";sleep 3")
	go runCommand(tmp)
	log.Println("runPingClick END")
}

func runTestExecClick(b *gui.GuiButton) {
	log.Println("runTestExecClick START")
	if runtime.GOOS == "linux" {
		go runSimpleCommand("xterm -report-fonts")
	} else if runtime.GOOS == "windows" {
		go runSimpleCommand("mintty.exe")
	} else {
		go runSimpleCommand("xterm")
	}
	log.Println("runTestExecClick END")
}

func runSimpleCommand(s string) {
	cmd := strings.TrimSpace(s) // this is like 'chomp' in perl
	cmd  = strings.TrimSuffix(cmd, "\n") // this is like 'chomp' in perl
        cmdArgs := strings.Fields(cmd)
	runCommand(cmdArgs)
}

func runCommand(cmdArgs []string) {
	log.Println("runCommand() START", cmdArgs)
	process := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
	// process := exec.Command("xterm", "-e", "ping localhost")
	log.Println("runCommand() process.Start()")
	process.Start()
	log.Println("runCommand() process.Wait()")
	process.Wait()
	log.Println("runCommand() NEED TO CHECK THE TIME HERE TO SEE IF THIS WORKED")
	log.Println("runCommand() OTHERWISE INFORM THE USER")
	log.Println("runCommand() END")
}

/*
	// just print config parsing worked
	for key, foo := range config.Accounts {
		log.Println("account =          ", key, foo)
		log.Println("Accounts[key] =    ", config.Accounts[key])
	}
	// config.Gitref = shell.Run("git rev-list -1 HEAD")

	config.Dirty = false

	if (tagref == config.Gitref) {
		log.Println("setting config.Dirty = false")
		config.Dirty = false
	} else {
		log.Println("setting config.Dirty = true")
		config.Dirty = true
	}

	log.Println("config.Gitref    =", config.Gitref)
	log.Println("config.Goversion =", config.Goversion)
	log.Println("config.Dirty     =", config.Dirty)

	log.Println("runtime.Version =", runtime.Version())
	log.Println("runtime Number of CPUs =", runtime.NumCPU())
	log.Println("runtime Number of GoRoutines =", runtime.NumGoroutine())

	log.Println("runtime.GOARCH =", runtime.GOARCH)

	stackSlice := make([]byte, 12512) // made this number up for no reason
	s := runtime.Stack(stackSlice, false)
	fmt.Printf("\n%s", stackSlice[0:s])
	// blah := runtime.Stack()
	spew.Dump(s)

	// bi, biok := debug.ReadBuildInfo()
	// log.Println("debug.BuildInfo() ok =", biok)
	// spew.Dump(bi.Path)
	// spew.Dump(bi.Main)
	// log.Println("debug.BuildInfo.Path =", bi.Path)

	errChan <- "hello"
	errChan <- fmt.Errorf("blah")

	handleSignal(nil, 0)
	// my pid (cross platform) p, err := os.FindProcess(os.Getpid())
	// send signal (cross platform) return p.Signal(syscall.SIGTERM)

	// for {}
	// os.Exit(0)
*/