package main

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/modcloth-labs/golog"
)

func main() {
	server, err := newCrispyServer()
	if err != nil {
		log.Fatal(err)
	}

	http.Handle("/", server)
	log.Printf("Serving on :9799 with %+v\n", server)
	log.Fatal(http.ListenAndServe(":9799", nil))
}

type crispyServer struct {
	logstasher *golog.Logger
}

func newCrispyServer() (*crispyServer, error) {
	logstasher, err := newLogstashLogger()
	if err != nil {
		return nil, err
	}
	return &crispyServer{logstasher: logstasher}, nil
}

func (me *crispyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	j, err := json.Marshal(r)
	if err == nil {
		if me.logstasher != nil {
			me.logstasher.Infof("%s", string(j))
		}
	}
}

func newLogstashLogger() (*golog.Logger, error) {
	logger := golog.NewLogger("")
	tcpProcessor, err := golog.NewTcpProcessorAt(":55784", golog.LOG_DEBUG)
	if err != nil {
		log.Printf("WARNING: %+v\n", err)
	}

	logger.AddProcessor("tcp", tcpProcessor)
	return logger, nil
}