package http

import (
	"fmt"
	"image/jpeg"
	"net/http"
	"time"

	"git.arav.su/Arav/httpr"
	captcha "git.arav.su/Arav/justcaptcha/v2"
	"git.arav.su/Arav/justcaptcha/v2/dwcaptcha"
	"git.arav.su/Arav/justcaptcha/v2/inmemdb"
)

type CaptchaApiHandlers struct {
	Expiry time.Duration
}

func NewCaptchaApiHandlers(expiry time.Duration) *CaptchaApiHandlers {
	inmemdb.SetExpiry(expiry)
	return &CaptchaApiHandlers{Expiry: expiry}
}

func (h *CaptchaApiHandlers) New(w http.ResponseWriter, r *http.Request) {
	dwc := dwcaptcha.NewDwellingCaptcha(h.Expiry)
	_, id := inmemdb.New(r.RemoteAddr, dwc)
	w.WriteHeader(http.StatusCreated)
	fmt.Fprint(w, id)
}

func (h *CaptchaApiHandlers) Solve(w http.ResponseWriter, r *http.Request) {
	captchaID := captcha.ID(httpr.Param(r, "id"))

	if r.URL.Query().Has("remove") {
		inmemdb.Remove(captchaID)
		w.WriteHeader(http.StatusNoContent)
		return
	}

	if solved := inmemdb.IsSolved(captchaID); !solved {
		http.Error(w, "wrong answer", http.StatusForbidden)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

func (h *CaptchaApiHandlers) Image(w http.ResponseWriter, r *http.Request) {
	id := captcha.ID(httpr.Param(r, "id"))

	image := inmemdb.Image(id, r.URL.Query().Get("style"))
	if image == nil {
		http.Error(w, "image not found", http.StatusNotFound)
		return
	}

	w.Header().Add("Content-Disposition", "inline; filename=\""+string(id)+"\"")

	jpeg.Encode(w, *image, &jpeg.Options{Quality: 20})
}
