package routes

import (
	"net/http"
	"strconv"
	"time"

	"gitea.henriburau.de/haw-lan/cod4watcher/models"
	"gitea.henriburau.de/haw-lan/cod4watcher/views/capture"
	"github.com/go-chi/chi"
)

func (s *Server) HandleCapture(w http.ResponseWriter, r *http.Request) error {
	captureString := chi.URLParam(r, "captureID")
	captureID, err := strconv.ParseInt(captureString, 10, 64)
	if err != nil {
		return err
	}

	foundCapture, err := s.cs.GetCaptureById(r.Context(), captureID)
	if err != nil {
		return err
	}

	return Render(w, r, capture.Capture(foundCapture))
}

func (s *Server) HandleCaptureDelete(w http.ResponseWriter, r *http.Request) error {
	captureString := chi.URLParam(r, "captureID")
	captureID, err := strconv.ParseInt(captureString, 10, 64)
	if err != nil {
		return err
	}

	err = s.cs.DeleteCapture(r.Context(), captureID)
	if err != nil {
		return err
	}

	return hxRedirect(w, r, "/")
}

func (s *Server) HandleCaptureForm(w http.ResponseWriter, r *http.Request) error {
	return Render(w, r, capture.CaptureForm(capture.CaptureFormValues{}, map[string]string{}))
}

func (s *Server) HandleCaptureCreate(w http.ResponseWriter, r *http.Request) error {
	formValues, errors := parseCaptureFormAndValidate(r)
	if len(errors) > 0 {
		return Render(w, r, capture.CaptureForm(formValues, errors))
	}

	newCapture := &models.Capture{
		Host:   formValues.Host,
		Port:   formValues.Port,
		Name:   formValues.Name,
		Active: true,
		Start:  time.Now(),
	}

	_, err := s.cs.GetServerStatus(r.Context(), newCapture)
	if err != nil {
		errors["host"] = err.Error()
		errors["port"] = err.Error()

		return Render(w, r, capture.CaptureForm(formValues, errors))
	}

	err = s.cs.CreateCapture(r.Context(), newCapture)
	if err != nil {
		return err
	}

	return hxRedirect(w, r, "/")
}

func parseCaptureFormAndValidate(r *http.Request) (capture.CaptureFormValues, map[string]string) {
	r.ParseForm()

	formValues := capture.CaptureFormValues{
		Host: r.FormValue("host"),
		Port: r.FormValue("port"),
		Name: r.FormValue("name"),
	}

	errors := map[string]string{}

	if len(formValues.Host) <= 0 {
		errors["host"] = "Host needs to be set"
	}

	if len(formValues.Port) <= 0 {
		errors["port"] = "Port needs to be set"
	}

	if len(formValues.Name) < 5 || len(formValues.Name) > 50 {
		errors["name"] = "Name needs to be between 5 and 50 characters long"
	}

	return formValues, errors
}
