package models_pages

import (
	"bytes"
	"fmt"
	"html/template"
	"main/tools"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

const (
	// Имя соответствующего шаблона
	PostsPageTmplName = "posts.gohtml"
)

type Posts map[PostLink]*Post

func LoadPosts(dir string) (Posts, error) {

	posts := Posts{}

	err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !f.IsDir() && strings.HasSuffix(f.Name(), ".md") {

			md, err := os.ReadFile(path)
			if err != nil {
				return err
			}

			html := tools.MdToHTML(md)
			link := fmt.Sprintf("/%s/", strings.TrimSuffix(filepath.Base(path), ".md"))
			timestamp := f.ModTime().Unix()
			posts[PostLink(link)] = newPost(link, html, timestamp)
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return posts, nil
}

func (p *Posts) RenderPostsPage(templates *template.Template, version int64) ([]byte, error) {
	var pageData bytes.Buffer

	postsSlice := make([]*Post, 0, len(*p))
	for _, post := range *p {
		postsSlice = append(postsSlice, post)
	}

	// Сортирую по ModTimestamp (новые сначала)
	sort.Slice(postsSlice, func(i, j int) bool {
		return postsSlice[i].Timestamp > postsSlice[j].Timestamp
	})

	context := map[string]any{
		"version":            version,
		"renderingTimestamp": time.Now().Unix(),
		"posts":              postsSlice,
	}

	if err := templates.ExecuteTemplate(&pageData, PostsPageTmplName, context); err != nil {
		return nil, err
	}

	return pageData.Bytes(), nil
}
