package server

import (
	"fmt"
	"time"

	"code.justin.tv/foundation/twitchserver"
	"goji.io/pat"

	"code.justin.tv/eventbus/clock/internal/handlers"
	rpc "code.justin.tv/eventbus/clock/rpc"
)

type Server struct {
	port      int
	debugPort int
}

func New(port, debugPort int) *Server {
	return &Server{port, debugPort}
}

func (s *Server) Start(done <-chan struct{}) error {
	twirpHandler := rpc.NewClockServer(s, nil)
	mux := twitchserver.NewServer()
	mux.Handle(pat.Post(rpc.ClockPathPrefix+"*"), twirpHandler)
	mux.HandleFunc(pat.Get("/health"), handlers.HealthCheck())
	conf := twitchserver.NewConfig()
	conf.Addr = fmt.Sprintf(":%d", s.port)
	conf.DebugAddr = fmt.Sprintf(":%d", s.debugPort)
	conf.GracefulTimeout = 10 * time.Second
	conf.Stop = done

	return twitchserver.ListenAndServe(mux, conf)
}
