package models_pages

import (
	"bytes"
	"html/template"
	"time"
)

type PostLink string

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

type Post struct {
	Link      PostLink
	Preview   template.HTML
	Data      template.HTML
	Timestamp int64
}

func RenderPostPage(templates *template.Template, version int64, data template.HTML) ([]byte, error) {
	var pageData bytes.Buffer

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

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

	return pageData.Bytes(), nil
}

func newPost(link string, data []byte, timestamp int64) *Post {
	previewBuf := make([]byte, 0, 503)

	if len(data) > 500 {
		previewBuf = append(previewBuf, data[:500]...)
		previewBuf = append(previewBuf, '.', '.', '.')
	} else {
		previewBuf = append(previewBuf, data...)
	}

	return &Post{
		Link:      PostLink(link),
		Preview:   template.HTML(previewBuf),
		Data:      template.HTML(data),
		Timestamp: timestamp,
	}
}
