// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import "log"
import "net/url"
import "time"

import "github.com/gorilla/websocket"

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

var gorillaConn *websocket.Conn

func gorillaReadProtobuf(conn *websocket.Conn) {
	for {
		log.Println("gorilla START gorillaReadProtobuf()", time.Now())
		mytype, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			return
		}
		if (mytype == websocket.BinaryMessage) {
			protobufMsg := new(pb.Event)
			err = proto.Unmarshal(message, protobufMsg)
			if (err != nil) {
				log.Printf("readConn() something fucked up happened in Unmarshal")
			}
			log.Printf("gorillaReadProtobuf() successfully read protobuf from gorilla websocket")
			addEvent(protobufMsg)
		} else {
			log.Printf("recv: %s", message)
			// log.Printf("type, err = ", mytype, err)
		}
		time.Sleep(time.Second)
		log.Println("gorilla END gorillaReadProtobuf()", time.Now())
	}
}

func websocketSendProtobuf(msg *pb.Event) {
	log.Println("websocketSendProtobuf() Event_Type =", msg.Type, "Event.Account.Nick =", msg.Account)

	if (gorillaConn == nil) {
		log.Println("websocketSendProtobuf() CAN NOT SEND (socket connection isn't open)")
		return
	}

	test, err := proto.Marshal(msg)
	if err != nil {
		log.Println("websocketSendProtobuf() Marshal failed SERIOUS ERROR", err)
		log.Println("websocketSendProtobuf() Marshal failed SERIOUS ERROR", err)
		log.Println("websocketSendProtobuf() Marshal failed SERIOUS ERROR", err)
		return
	}

	err2 := gorillaConn.WriteMessage(websocket.BinaryMessage, test)
	if err2 != nil {
		log.Println("websocketSendProtobuf() WriteMessage() failed write:", err2)
		gorillaConn = nil
		return
	}
	log.Println("websocketSendProtobuf() END OK", time.Now())
}

func closeGorillaConn() {
	if gorillaConn == nil {
		log.Println("gorillaConn already was nil")
		return
	}

	// Cleanly close the connection by sending a close message and then
	// waiting (with timeout) for the server to close the connection.
	err := gorillaConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
	if err != nil {
		log.Println("write close:", err)
		return
	}

	// this must be called or set to be called with defer
	gorillaConn.Close()
	gorillaConn = nil
	log.Println("closeGorillaConn() END OK", time.Now())
}

func gorillaDial(hostname string) {
	// var addr = flag.String("addr", "v000185.testing.com.customers.wprod.wit.com:9000", "http service address")

	for {
		u := url.URL{
			Scheme: "ws",
			Host: hostname,
			Path: "/event",
		}
		log.Printf("connecting to %s", u.String())

		conn, resp, err := websocket.DefaultDialer.Dial(u.String(), nil)
		if err != nil {
			log.Println("gorillaDial failed", err)
		} else {
			resp.Header.Set("jcarrname", "jcarrvalue")
			gorillaConn = conn
			origconn := conn.UnderlyingConn()

			laddr := origconn.LocalAddr()
			raddr := origconn.RemoteAddr()
			log.Println("RESPONSE HEADER origconn.LocalAddr()= ",  laddr)
			log.Println("RESPONSE HEADER origconn.RemoteAddr()= ", raddr)

			// handle inbound messages on the channel
			gorillaReadProtobuf(conn)
			closeGorillaConn()
		}

		time.Sleep(time.Second * 5) // try every 5 seconds
	}
}
