package handlers

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

type Handler struct {
	Jobs <-chan *monitor.Item
	config.Stoppable
}

func New(jobs <-chan *monitor.Item) *Handler {
	return &Handler{
		Jobs: jobs,
	}
}

func (h *Handler) Run() error {
	for {
		select {
		case <-h.Stopped():
			return nil
		case j := <-h.Jobs:
			go func(key string) {
				if err := h.Job(key); err != nil {
					log.Println("[h.Run]", err)
				}
			}(j.Key)
		}
	}
}

func (h *Handler) Job(key string) error {
	f := &rss.Feed{Key: key}
	if err := f.Load(); err != nil {
		return err
	}
	if err := f.Pull(); err != nil {
		return err
	}
	return nil
}
