package api

import (
	"errors"
	"net/http"

	"github.com/nlopes/slack"

	"code.justin.tv/common/config"
	"code.justin.tv/common/twitchhttp"
	"goji.io"
	"goji.io/pat"
	"golang.org/x/net/context"
)

type Server struct {
	*goji.Mux

	Config *ServerConfig

	slack *slack.Slack
}

type ServerConfig struct {
	SlackToken string
}

func EnableSlackbot() bool {
	return config.Resolve("ENABLE_SLACKBOT") != ""
}

func NewServerConfig() (*ServerConfig, error) {

	var slackToken string
	if EnableSlackbot() {
		slackToken = config.Resolve("SLACK_TOKEN")
		if slackToken == "" {
			return nil, errors.New("SLACK_TOKEN cannot be empty")
		}
	}

	return &ServerConfig{
		SlackToken: slackToken,
	}, nil
}

func NewServer() (*Server, error) {
	config, err := NewServerConfig()
	if err != nil {
		return nil, err
	}

	server := twitchhttp.NewServer()

	s := &Server{
		Mux:    server,
		Config: config,
	}

	if EnableSlackbot() {
		s.slack = slack.New(config.SlackToken)
	}

	// Add your own endpoints here. Endpoint implementation should be defined as functions on Server.
	// For example: s.HandleFuncC(pat.Get("/my/path"), s.myEndpoint)
	// https://godoc.org/goji.io

	s.HandleFuncC(pat.Get("/"), s.EverythingIsFine)
	s.HandleFuncC(pat.Get("/health"), s.EverythingIsFine)
	s.HandleFuncC(pat.Get("/debug/running"), s.EverythingIsFine)
	return s, nil
}

func (s *Server) EverythingIsFine(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("OK"))
}
