package main

import (
	"net/http"
	"strings"
	"time"

	"github.com/gorilla/mux"
)

func handleRssFeed(w http.ResponseWriter, req *http.Request) {
	page := initPageData(w, req)

	vars := mux.Vars(req)
	var uid string
	var uidOk bool
	if uid, uidOk = vars["uid"]; !uidOk {
		userError(w)
		return
	}
	w.Header().Set("Content-Type", "application/xml")
	var slug string
	var slugOk bool
	slug, slugOk = vars["slug"]
	if !slugOk {
		// Print the user's entire feed
		buildUserRssFeed(page, uid)
	} else {
		// Print the feed for a specific slug
		buildSlugRssFeed(page, uid, slug)
	}
}

type rssPageData struct {
	User      *User
	Feeds     []Feed
	BuildDate time.Time
}

func buildUserRssFeed(page *pageData, uid string) {
	var err error
	rpd := new(rssPageData)
	rpd.BuildDate = time.Now()
	rpd.User, err = m.GetUser(uid)
	if err != nil {
		userError(page.session.w)
		return
	}
	for _, v := range rpd.User.SubSlugs {
		pts := strings.Split(v, ";")
		fd, err := m.GetFeed(pts[0], pts[1])
		if err != nil {
			userError(page.session.w)
			return
		}
		rpd.Feeds = append(rpd.Feeds, *fd)
	}
	page.TemplateData = rpd
	page.showRss()
}

func buildSlugRssFeed(page *pageData, uid, slug string) {
	var err error
	rpd := new(rssPageData)
	rpd.BuildDate = time.Now()
	rpd.User, err = m.GetUser(uid)
	if err != nil {
		userError(page.session.w)
		return
	}
	page.TemplateData = rpd
	page.showRss()
}
