package server

import (
	"fmt"
	"local/dndex/config"
	"local/dndex/storage"
	"local/router"
	"net/http"
)

type REST struct {
	port   int
	router *router.Router
	g      storage.RateLimitedGraph
}

type RESTScope struct {
	entity scope
	user   scope
}
type scope struct {
	name string
	id   string
}

func Listen(g storage.RateLimitedGraph) error {
	rest, err := NewREST(g)
	if err != nil {
		return err
	}
	return http.ListenAndServe(fmt.Sprintf(":%d", rest.port), rest.router)
}

func NewREST(g storage.RateLimitedGraph) (*REST, error) {
	rest := &REST{
		g:      g,
		port:   config.New().Port,
		router: router.New(),
	}

	param := router.Wildcard
	params := router.Wildcard + router.Wildcard
	_, _ = param, params

	paths := map[string]http.HandlerFunc{
		fmt.Sprintf("version"): rest.version,
		fmt.Sprintf("files/%s/%s", config.New().FilePrefix, params): rest.files,
		fmt.Sprintf("users"):               rest.users,
		fmt.Sprintf("entities/%s", params): rest.entities,
	}

	for path, foo := range paths {
		bar := foo
		bar = rest.auth(bar)
		bar = rest.defend(bar)
		bar = rest.delay(bar)
		if err := rest.router.Add(path, bar); err != nil {
			return nil, err
		}
	}

	return rest, nil
}

func (rest *REST) scope(r *http.Request) RESTScope {
	value, _ := r.Context().Value(AuthKey).(RESTScope)
	return value
}

func (rest *REST) files(w http.ResponseWriter, _ *http.Request) {
}

func (rest *REST) users(w http.ResponseWriter, _ *http.Request) {
}

func (rest *REST) entities(w http.ResponseWriter, _ *http.Request) {
}
