package main

import (
	"crowsnest/internal/model"
	"html/template"
	"net/http"
)

// List the latest articles using the base template. 
func (app *App) Index(w http.ResponseWriter, req *http.Request) {
    // get articles
    articles, err := app.articles.All()
    if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError); return; }

    // truncate
    if len(articles) > 10 {
        articles = articles[:10]
    }

    // convert to viewmodel
    articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
    for _, a := range articles {
        articleVMs = append(articleVMs, a.ViewModel())
    }

    // render template
    t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
    err = t.ExecuteTemplate(w, "base", articleVMs)
    if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
}
