package lib

import (
	"encoding/json"
	"errors"
	"html/template"
	"os"
	"path"
	"strings"
)

const CONTENT_PATH string = "content"

type Content struct {
	Dir  string
	Name string

	Title string `json:"title"`
	ID    string `json:"id"`

	Md   string
	HTML template.HTML

	Date   string `json:"date"`
	Author string `json:"author"`
}

func ListContent(dir string) ([]Content, error) {
	var res []Content

	dirpath := path.Join(CONTENT_PATH, dir)
	entries, err := os.ReadDir(dirpath)
	if err != nil {
		return nil, errors.New("Cannot readdir: " + dirpath)
	}

	for _, e := range entries {
		if e.IsDir() {
			subres, err := ListContent(path.Join(dir, e.Name()))
			if err != nil {
				return res, err
			}
			res = append(res, subres...)
		}

		if !strings.HasSuffix(e.Name(), ".json") {
			continue
		}

		var con Content
		jsonfile := path.Join(dirpath, e.Name())
		jsoncon, err := os.ReadFile(jsonfile)

		if err != nil {
			return nil, errors.New("Cannot get JSON: " + jsonfile)
		}

		err = json.Unmarshal(jsoncon, &con)
		if err != nil {
			return nil, errors.New("Cannot parse JSON: " + jsonfile)
		}

		con.Dir = dir
		con.Name = strings.Split(e.Name(), ".")[0]
		res = append(res, con)
	}

	return res, nil
}

func GetContent(dir string, name string) (Content, error) {
	var res Content
	jsonfile := path.Join(CONTENT_PATH, dir, name+".json")
	mdfile := path.Join(CONTENT_PATH, dir, name+".md")

	res.Dir = dir
	res.Name = name

	jsoncontent, err := os.ReadFile(jsonfile)
	if err != nil {
		return res, errors.New("Cannot read JSON file: " + jsonfile)
	}

	rawcontent, err := os.ReadFile(mdfile)
	if err != nil {
		return res, errors.New("Cannot read markdown file: " + mdfile)
	}

	if json.Unmarshal(jsoncontent, &res) != nil {
		return res, errors.New("Cannot parse JSON: " + jsonfile)
	}

	res.Md = string(rawcontent)
	res.HTML = template.HTML(ParseMarkdown(res.Md))
	return res, nil
}
