package rss

import (
	"local/rssmon3/config"
	"local/rssmon3/monitor"
	"log"
)

type RSS struct {
	items chan *monitor.Item
	config.Stoppable
}

func New(items chan *monitor.Item) *RSS {
	return &RSS{
		items: items,
	}
}

func (rss *RSS) Run() error {
	for {
		select {
		case <-rss.Stopped():
			return nil
		case i := <-rss.items:
			if err := rss.update(i); err != nil {
				log.Println("[rss.Run]", err)
			}
		}
	}
}

func (rss *RSS) update(item *monitor.Item) error {
	f := newFeed(item.Key)
	if err := f.Pull(); err != nil {
		return err
	}
	if err := f.save(); err != nil {
		return err
	}
	return nil
}
