package server

import (
	"io"
	"local/dndex/config"
	"local/gziphttp"
	"net/http"
	"time"
)

func (rest *REST) delay(foo http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		select {
		case <-time.After(config.New().Delay):
			foo(w, r)
		case <-r.Context().Done():
			http.Error(w, r.Context().Err().Error(), 499)
		}
	}
}

func (rest *REST) defend(foo 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
		}
		r.Body = struct {
			io.Reader
			io.Closer
		}{
			Reader: io.LimitReader(r.Body, config.New().MaxFileSize),
			Closer: r.Body,
		}
		foo(w, r)
	}
}

func (rest *REST) auth(foo http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := Auth(rest.g, w, r); err != nil {
			return
		}
		foo(w, r)
	}
}
