package main

import "log"

import "github.com/golang/protobuf/proto"
import pb "git.wit.com/wit/witProtobuf"
import "git.wit.com/wit/gui"

var mychannel chan *pb.Event
var currentMessage *pb.Event

func initChannel() {
	mychannel = make(chan *pb.Event)
}

// Marshal & Unmarshal just to see if it ever fails
func addEvent(msg *pb.Event) {
	data, err := proto.Marshal(msg)
	if (err != nil) {
		log.Printf("addEvent() something fucked up happened in Marshal")
	}

	pdata := new(pb.Event)
        err = proto.Unmarshal(data, pdata)
	if (err != nil) {
		log.Printf("addEvent() something fucked up happened in Unmarshal")
	}

	mychannel <- pdata
}

// func processEvents(mychannel chan *pb.Event) {
func processEvents() {
	defer r() // a golang trick to try to not crash on certain errors
	for {
		currentMessage = <-mychannel
		log.Println("processEvents() RECIEVED msg = ", currentMessage)
		if (currentMessage.Type == pb.Event_DEMO) {
			log.Println("processEvents() do Event DEMO")
		} else {
			log.Println("processEvents() NEW PROTOBUF")
			State = "NEW PROTOBUF"
		}
		log.Println("processEvents() END on channel")
	}
}

func countVMS(data *pb.Event) int {
	vms := data.GetVms()
	log.Println("NUMBER OF vms=", len(vms))
	// os.Exit(-1)
	return len(vms)
}

func ReadReceivedData(data *pb.Event, mh *gui.TableData, box *gui.GuiBox) {
	msgItems := data.GetResults()
	log.Println("ReadReceivedData() Event msgItems=", msgItems)
	for _, item := range msgItems {
		log.Println(item)
	}

	nets := data.GetNetworks()
	log.Println("ReadReceivedData() Event networks=", nets)
	for _, item := range nets {
		log.Println(item)
	}

	vms := data.GetVms()
	log.Println("ReadReceivedData() Event vms=", vms)
	for row, vm := range vms {
		setRowValues(mh, row, vm)

		// create entries for the mouse clicks within tables
		var newGuiButton gui.GuiButton
		newGuiButton.Custom	= showVmMouseClick
		if (box.Window == nil) {
			panic("ReadReceivedData() box == nil")
		}
		newGuiButton.Box        = mh.Box
		newGuiButton.Values     = makeGuiButtonValues(box, data.Account, vm, "JWC", "SHOW VM 33", showVmMouseClick)
		gui.Data.AllButtons     = append(gui.Data.AllButtons, &newGuiButton)
		mh.Rows[row].HumanData[6].Button = &newGuiButton

		log.Println("\tvm.Name=", vm.Name, mh.Rows[row].Name)
		row += 1
	}
}
