package rss

import (
	"bytes"
	"log"
	"os"
	"testing"
)

func initRSSSerialize() {
	initRSSFeed()
}

func TestRSSTaggedFeeds(t *testing.T) {
	initRSSFeed()

	for _, k := range []string{"a", "b"} {
		f := newFeed(k)
		f.Tags = []string{"TAG"}
		if err := f.save(); err != nil {
			t.Fatal(err)
		}
	}

	if feeds, err := TaggedFeeds("NOTTAG"); err != nil {
		t.Fatal(err)
	} else if len(feeds) != 0 {
		t.Fatal(len(feeds))
	}

	if feeds, err := TaggedFeeds("TAG"); err != nil {
		t.Fatal(err)
	} else if len(feeds) != 2 {
		t.Fatal(len(feeds))
	} else {
		t.Logf("%v", feeds)
	}
}

func TestRSSWriteFeed(t *testing.T) {
	initRSSFeed()
	s := mockRSS()
	defer s.Close()

	f := newFeed("key")
	f.TitleFilter = "5[0-9]{2}"
	f.ContentFilter = "b"
	f.Tags = []string{"c"}
	f.URL = s.URL
	f.Copyright = "copyright"

	log.SetOutput(bytes.NewBuffer(nil))
	defer log.SetOutput(os.Stderr)
	if err := f.Pull(); err != nil {
		t.Fatal(err)
	}
	log.SetOutput(os.Stderr)

	items, err := f.Items(5)
	if err != nil {
		t.Fatal(err)
	}
	if len(items) != 5 {
		t.Fatal(len(items))
	}

	buff := bytes.NewBuffer(nil)
	if err := WriteFeed(buff, "c", items); err != nil {
		t.Fatal(err)
	}
	t.Logf("%s", buff.Bytes())
}
