package server

import (
	"local/firestormy/config"
	"local/gziphttp"
	"local/oauth2/oauth2client"
	"local/router"
	"log"
	"net/http"
	"path/filepath"
)

type Server struct {
	*router.Router
	fileServer http.Handler
}

func New() *Server {
	return &Server{
		Router:     router.New(),
		fileServer: http.FileServer(http.Dir(config.Root)),
	}
}

func (s *Server) authenticate(foo http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if config.OAuthServer != "" {
			err := oauth2client.Authenticate(config.OAuthServer, "firestormy", w, r)
			if err != nil {
				log.Println(err)
				return
			}
		}
		foo(w, r)
	}
}

func (s *Server) gzip(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if gziphttp.Can(r) {
			gz := gziphttp.New(w)
			defer gz.Close()
			w = gz
		}
		if filepath.Ext(r.URL.Path) == ".css" {
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
		}
		h(w, r)
	}
}
