package main

import "log"
import "fmt"
import "time"

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

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

// This sends a login protocol buffer and waits for a response

func login(b *gui.GuiButton) {
	log.Println("login() START")
	State   = "SEND LOGIN"

	// TODO: move this into a seperate goroutine
	// note: this may never be possible because of cross platform
	// andlabs/ui requirements. windows and macos seem to freak out
	// when you try to trigger the UI in seperate threads

	values, _ := b.Values.(*myButtonInfo)
	event := pb.MakeLoginEvent()
	event.Account = values.Account
	websocketSendProtobuf(event)


	count := 0
	for {
		log.Println("\tSleep() in buttonClick() State =", State)
		time.Sleep(200 * time.Millisecond)
		if (State == "NEW PROTOBUF") {
			if (currentMessage == nil) {
				gui.ErrorWindow(b.Box.Window,
					"There was a socket error",
					"More detailed information can be shown here.")
				State = "done"
			} else {
				log.Println("LOGIN currentMessage =", currentMessage)
				if (currentMessage.Type == pb.Event_OK) {
					msg := "On account " + values.Account.Nick + "\n"
					log.Println("\tLOGIN WAS OK!", msg)
					log.Println("\tLOGIN WAS OK! old button.Account was =", values.Account)
					log.Println("\tLOGIN WAS OK! currentMessage.Account =", currentMessage.Account)
					if (values.Account.Id == currentMessage.Account.Id) {
						if (values.Account.Token != currentMessage.Account.Token) {
							log.Println("\tLOGIN SENT NEW TOKEN")
							values.Account.Token = currentMessage.Account.Token
							log.Println("\tLOGIN WAS OK! old button.Account is now =", values.Account)
						}
					}
					log.Println("\tLOGIN WAS OK!")
					gui.MessageWindow(b.Box.Window, "Login OK", msg)
				} else if (currentMessage.Type == pb.Event_FAIL) {
					log.Println("\tLOGIN FAILED")
					log.Println("\tLOGIN FAILED")
					log.Println("\tLOGIN FAILED")
					msg := "On account " + values.Account.Nick + "\n"
					msg += "pb.Comment = " + currentMessage.Comment + "\n"
					msg += "pb.Id = " + fmt.Sprintf("%d", currentMessage.Id) + "\n"
					msg += "pb.Email = " + values.Account.Email + "\n"
					msg += "pb.Username = " + values.Account.Username + "\n"
					gui.ErrorWindow(b.Box.Window, "Login Failed", msg)
				}
				currentMessage = nil
				State = "done"
			}
			return
		}
		// TODO: fix this with an actual timeout
		count += 1
		if (count > 10) {
			gui.ErrorWindow(b.Box.Window, "Network Timeout", "ERROR: waited too long for a resposne")
			currentMessage = nil
			State = "done"
			return
		}
	}
}
