package main

import (
	"io/fs"
	"log"
	"os"
	"path"
	"encoding/base64"

	"net/http"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"

	"git.madunde.ad/madundead/obi/routers"
)

func main() {
	router := gin.Default()
	router.SetTrustedProxies([]string{"127.0.0.1"}) // TODO: fix All origins allowed by default
	router.Use(cors.Default())

	list := listFiles("/home/madundead/Syncthing/Obsidian/Personal")

	router.GET("/api/v1/files", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"data":   list,
			"status": "ok",
		})
	})

	router.GET("/api/v1/files/:id", func(c *gin.Context) {
		id := c.Params.ByName("id")
    path, _ := base64.StdEncoding.DecodeString(id)

    data, _ := os.ReadFile(string(path))

		c.JSON(http.StatusOK, gin.H{"data": string(data)})
	})

	if err := router.Run(); err != nil {
		panic(err)
	}
}

func listFiles(dir string) []string {
	root := os.DirFS(dir)

	mdFiles, err := fs.Glob(root, "**/*.md")

	if err != nil {
		log.Fatal(err)
	}

	var files []string
	for _, v := range mdFiles {
		files = append(files, path.Join(dir, v))
	}
	return files
}
//
// func readFile(string filePath) []string {
// 	content, err := os.ReadFile(filePath)
// 	if err != nil {
// 		fmt.Println("Error reading file:", err)
// 		return
// 	}
// 	return content
// }
