package main

import (
	"fmt"
	"net/http"

	"golang.org/x/oauth2"

	"code.justin.tv/release/forge/internal/environments"
	"code.justin.tv/release/forge/internal/modules"

	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"
	"github.com/zenazn/goji/web/middleware"
)

func InitializeApi() {
	goji.Get("/running", HealthCheck)
	goji.Get("/whoami", whoami)
	goji.Get("/github_callback", GithubCallback)
	api := web.New()
	goji.Handle("/v1/*", api)

	api.Get("/modules", modules.Index)
	api.Get("/modules/:name", modules.Show)

	api.Post("/environments", environments.Create)
	api.Get("/environments/:name", environments.Show)
	api.Put("/environments/:name", environments.Update)
	api.Delete("/environments/:name", environments.Destroy)
	api.Post("/environments/:name/refresh", environments.Refresh)

	// Router will populate the web.C env with information about the match, the
	// pattern etc.
	api.Use(goji.DefaultMux.Router)
	api.Use(RecoverPanics)
	api.Use(ChitinMiddleware)
	api.Use(StatsdMiddleware)

	// See https://github.com/zenazn/goji/blob/eaa649ab77fd613bb3d44dde6b4e6043a01eee66/web/mux.go#L113
	api.Use(middleware.SubRouter)

	api.Use(GithubMiddleware)
}

func HealthCheck(c web.C, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, `{"status": "running", "status_code": 200}`)
}

func GithubCallback(w http.ResponseWriter, r *http.Request) {
	token, err := oauthConfig.Exchange(oauth2.NoContext, r.FormValue("code"))
	if err == nil {
		fmt.Println(token)
		// TODO: now store the token in the db
	}
}
