package api

import (
	"encoding/json"
	"net/http"
	"os"
	"path/filepath"
)

type FileData struct {
	ImageNames      []string
	SpicyImageNames []string
	AsciiFiles      []AsciiEntry
}

type AsciiEntry struct {
	Name     string
	FontSize int
}

const staticDir = "static"

// move FileData and AsciiEntry here if you want, or leave in main.go
func FileHandler(w http.ResponseWriter, r *http.Request) {
	data := FileData{
		ImageNames:      []string{},
		SpicyImageNames: []string{},
		AsciiFiles:      []AsciiEntry{},
	}

	files, _ := os.ReadDir(filepath.Join(staticDir, "images"))
	for _, file := range files {
		fileName := file.Name()
		data.ImageNames = append(data.ImageNames, filepath.Join("/", staticDir, "images", fileName))
	}
	files, _ = os.ReadDir(filepath.Join("uploads"))
	for _, file := range files {
		fileName := file.Name()
		data.ImageNames = append(data.ImageNames, filepath.Join("/uploads", fileName))
	}

	files, _ = os.ReadDir(filepath.Join(staticDir, "spicy"))
	for _, file := range files {
		fileName := file.Name()
		data.ImageNames = append(data.ImageNames, filepath.Join("/", staticDir, "spicy", fileName))
	}

	files, _ = os.ReadDir(filepath.Join(staticDir, "ascii_art"))
	for _, file := range files {
		fileName := file.Name()
		data.AsciiFiles = append(data.AsciiFiles,
			AsciiEntry{Name: filepath.Join("/", staticDir, "ascii_art", fileName), FontSize: 12},
		)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(data)
}
