package flowserver

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"

	"github.com/gohxs/prettylog"
	"github.com/gohxs/webu"
	"github.com/gohxs/webu/chain"
)

//go:generate go get github.com/gohxs/genversion
//go:generate genversion -package flowserver -out version.go
//

// FlowServer structure
type FlowServer struct{}

// ListenAndServe starts the httpserver
// It will listen on default port 2015 and increase if port is in use
func (f *FlowServer) ListenAndServe() error {
	fsm := NewFlowSessionManager()

	c := chain.New(webu.ChainLogger(prettylog.New("req")))

	mux := http.NewServeMux()
	mux.Handle("/conn", c.Build(fsm.ServeHTTP))

	if os.Getenv("DEBUG") == "1" {
		log.Println("DEBUG MODE: reverse proxy localhost:8081")
		proxyURL, err := url.Parse("http://localhost:8081")
		if err != nil {
			return err
		}
		mux.Handle("/", c.Build(httputil.NewSingleHostReverseProxy(proxyURL).ServeHTTP))
	} else {
		mux.Handle("/", c.Build(webu.StaticHandler("web", "index.html")))
	}

	////////////////////
	// Server starter
	/////
	port := 2015
	for {
		addr := fmt.Sprintf(":%d", port)
		s, err := net.Listen("tcp", addr)
		if err != nil {
			log.Println("Listen error:", err)
			port++
			continue
		}
		log.Println("Listening at:", addr)
		err = http.Serve(s, mux)
		if err != nil {
			log.Fatal(err)
		}
	}
}
