// 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 "flag"
import "log"
import "net/url"
import "os"
import "os/signal"
import "time"

import "github.com/gorilla/websocket"

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

var gorillaConn *websocket.Conn

func readGorillaConn(conn *websocket.Conn) {
	for {
		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("readGorillaConn() 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 readGorillaConn()", time.Now())
	}
}

func gorillaSendProtobuf() {
	if (gorillaConn == nil) {
		log.Println("gorillaSendProtobuf() gorillaConn == nil")
		log.Println("Need to re-open connection here")
		return
	}
	msg := pb.CreateSampleEvent()
	msg.Name = "test echo over gorilla websocket"
	data, _ := proto.Marshal(msg)
	err2 := gorillaConn.WriteMessage(websocket.BinaryMessage, data)
	if err2 != nil {
		log.Println("write:", err2)
		gorillaConn = nil
		return
	}
}

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
}

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: *addr, Path: "/event"}
		u := url.URL{Scheme: "ws", Host: hostname, Path: "/event"}
		log.Printf("connecting to %s", u.String())

		conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
		if err != nil {
			log.Println("gorilla Dial failed", err)
		} else {
			gorillaConn = conn

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

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

//
// this is a facinating code snippet that I wanted to leave here because it is
// so interesting. Complements to the gorilla websocket example developers
//
func beautifulAndFacinatingChannel() {
	done := make(chan struct{})

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	ticker := time.NewTicker(time.Second * 1)

	defer ticker.Stop()
	defer close(done)

	for {
		select {
		case <-done:
			return
		case t := <-ticker.C:
			log.Println("gorilla NewTicker()", t.String())
		case <-interrupt:
			log.Println("interrupt")

			gorillaSendProtobuf()

			// not sure what this does. nothing right?
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			return
		}
	}
}