package rss

import (
	"fmt"
	"io"
	"local/rssmon3/config"
	"sort"

	"github.com/gorilla/feeds"
)

func TaggedFeeds(tag string) ([]*Feed, error) {
	db := config.Values().DB
	feedNames, err := db.List([]string{nsFeeds})
	if err != nil {
		return nil, err
	}
	results := []*Feed{}
	for _, feedName := range feedNames {
		f := newFeed(feedName)
		if err := f.Load(); err != nil {
			return nil, err
		}
		for i := range f.Tags {
			if f.Tags[i] == tag {
				results = append(results, f)
			}
		}
	}
	return results, nil
}

func WriteFeed(w io.Writer, tag string, items []*Item) error {
	sort.Sort(Items(items))
	feed := &feeds.Feed{
		Title:       tag,
		Link:        &feeds.Link{},
		Description: tag,
		Items:       make([]*feeds.Item, len(items)),
	}
	for i, item := range items {
		feed.Items[i] = &feeds.Item{
			Title:       item.Title,
			Link:        &feeds.Link{Href: item.Link},
			Description: item.Content,
			Author:      &feeds.Author{Name: item.Copyright},
			Created:     item.TS,
		}
	}
	s, err := feed.ToRss()
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "%s\n", s)
	return nil
}
