package database

import (
	"fmt"
)

type Link struct {
	ID               int
	TitleSlug        string `db:"title_slug""`
	Year, Month, Day int
	Title            string `db:"post_title"`
}

func (l *Link) GemtextLink() string {
	return fmt.Sprintf("=> /p/%d/%s %d-%d-%d - %s\n", l.ID, l.TitleSlug, l.Year, l.Month, l.Day, l.Title)
}

func (l *Link) GemtextArchiveLink() string {
	return fmt.Sprintf("=> /y/%d/ Godina %d.\n", l.Year, l.Year)
}

func (l *Link) GemtextArchiveMonthLink() string {
	return fmt.Sprintf("=> /y/%d/m/%d/ %d-%d\n", l.Year, l.Month, l.Year, l.Month)
}

func (l *Link) HTMLLink() string {
	return fmt.Sprintf("<a href=\"/p/%d/%s\">%d-%d-%d - %s</a><br>\n", l.ID, l.TitleSlug, l.Year, l.Month, l.Day, l.Title)
}

func (l *Link) HTMLArchiveLink() string {
	return fmt.Sprintf("<a href=\"/y/%d/\">Godina %d.</a><br>\n", l.Year, l.Year)
}

func (l *Link) HTMLArchiveMonthLink() string {
	return fmt.Sprintf("<a href=\"/y/%d/m/%d/\">%d-%d</a><br>\n", l.Year, l.Month, l.Year, l.Month)
}

func GetRecentLinks() ([]Link, error) {
	db := GetDB()
	links := []Link{}
	err := db.Select(&links, "SELECT id, title_slug, year, month, day, post_title FROM posts ORDER BY date DESC LIMIT 10")
	if err != nil {
		return nil, err
	}
	return links, nil
}

func GetLinksByMonth(year, month int) ([]Link, string, error) {
	db := GetDB()
	links := []Link{}

	err := db.Select(&links, "SELECT id, title_slug, year, month, day, post_title FROM posts WHERE year = ? and month = ? ORDER BY date desc", year, month)
	if err != nil {
		return nil, "", err
	}

	return links, fmt.Sprintf("# Arhiva za %d-%d\n\n", year, month), nil
}

func GetMonthLinksByYear(year int) ([]Link, string, error) {
	db := GetDB()
	links := []Link{}

	err := db.Select(&links, "SELECT distinct month, year FROM posts WHERE year = ? ORDER BY month DESC", year)
	if err != nil {
		return nil, "", err
	}

	return links, fmt.Sprintf("# Arhiva za %d\n\n", year), nil
}

func GetAllYearLinks() ([]Link, string, error) {
	db := GetDB()
	links := []Link{}

	err := db.Select(&links, "SELECT distinct year FROM posts ORDER BY year DESC")
	if err != nil {
		return nil, "", err
	}

	return links, fmt.Sprintf("# Arhiva: "), nil
}
