package babillard

import (
	"fmt"
	"log"
	"net/http"
	"strings"

	"github.com/labstack/echo/v4"
)

// pre-v2

type ContenuHandler struct {
	ContenuDir string
}

func NewContenuHandler(contenuDir string) (h ContenuHandler) {
	h.ContenuDir = contenuDir
	return
}

func (h ContenuHandler) HandleAPIContenuList(c echo.Context) error {
	contenu_dir := h.ContenuDir

	files, err := ListContenu(contenu_dir)
	if err != nil {
		log.Println(err)
		return c.JSON(http.StatusInternalServerError, map[string]string{
			"message": "Internal Server Error",
			"error":   err.Error(),
		})
	}

	return c.String(http.StatusOK, strings.Join(files, ";"))
}

func (h ContenuHandler) HandleAPIContenuFile(c echo.Context) error {
	filename := c.Param("filename")
	contenu_dir := h.ContenuDir

	if filename == ".gitkeep" {
		return c.JSON(http.StatusNotFound, map[string]string{"message": "Not Found"})
	}

	return c.File(fmt.Sprintf("%s/%s", contenu_dir, filename))
}

// v2

func APIv2ListContenu(cfg Config) echo.HandlerFunc {
	return func(c echo.Context) error {
		files, err := ListContenu(cfg.ServerContenuDir)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		}

		return c.JSON(http.StatusOK, NewContenuResponse(files))
	}
}

// ui

func UIContenuFichier(cfg Config) echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.File(fmt.Sprintf("%s/%s", cfg.ServerContenuDir, c.Param("fichier")))
	}
}