{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Handler.Feed where

import Lounge
import Storage
import Settings
import Common

import Model.Entry

import Data.Time.Clock.POSIX

import Yesod.Helpers.AtomFeed

getFeedR :: Handler RepAtom
getFeedR = do
	entries <- liftIO $ runLSM Settings.connStr $ loadEntriesByDate
	renderFeed entries

getTagFeedR :: Tag -> Handler RepAtom
getTagFeedR tag = do
	entries <- (liftIO $ runLSM Settings.connStr $ loadEntriesByTag tag)
	renderFeed entries

renderFeed :: [(EntryId, Entry)] -> Handler RepAtom
renderFeed entries = do
	let entries' = take 5 entries
	atomFeed $ AtomFeed
		{ atomTitle = title
		, atomLinkSelf = FeedR
		, atomLinkHome = EntriesR
		, atomUpdated = if null entries' then posixSecondsToUTCTime 0 else eTimestamp $ snd $ head entries'
		, atomEntries = map go entries'
		}
	where
		go e = AtomFeedEntry
			{ atomEntryLink = EntryR $ fst e
			, atomEntryUpdated = eTimestamp $ snd e
			, atomEntryTitle = eTitle $ snd e
			, atomEntryContent = preEscapedString $ eText $ snd $ e
			}


