--------------------------------------------------------------------
-- |
-- Module    : hackage2hwn
-- Copyright : (c) Galois, Inc. 2007-2008
-- License   : BSD3
--
-- Maintainer: Don Stewart <dons@galois.com>
-- Stability : provisional
--
-- Pulls the RSS feed from Hackage, pretty prints it in a form suitable for
-- inclusion in the Haskell Weekly News.
--
--------------------------------------------------------------------

module Main (main) where

import Data.Maybe
import Data.List
import Data.Char

import Network.Download
import Text.HTML.TagSoup

import Text.Feed.Import
import Text.RSS.Syntax
import Text.Feed.Types

import Debug.Trace

url = "http://hackage.haskell.org/packages/archive/recent.rss"

main = do
    putStrLn "'''Recent Package Updates''' [http://haskell.org/haskellwiki/Hackage_statistics http://galois.com/~dons/images/hackage-daily.png] [http://hackage.haskell.org/packages/archive/recent.rss http://haskell.org/sitewiki/images/0/09/Rss.png]\n"

    Right src         <- openURIString url
    let Just (RSSFeed is) = parseFeedString src
    mapM_ (putStr . pprRSS) (clean . rssItems . rssChannel $ is)
    putStrLn $ "[http://hackage.haskell.org/packages/archive/pkg-list.html More...]"

pprRSS :: RSSItem -> String
pprRSS r = unlines
            [(";" ++ "[" ++ url ++ " "++  title ++ "]")
            ,(":" ++ synopsis)]
   where
     Just title    = rssItemTitle $ r
     Just url      = rssItemLink $ r

     -- May not be the actual synopsis. Parse the .cabal file instead?
     synopsis = last [ e | TagText e <- parseTags
                             (fromJust . rssItemDescription $ r) ]

clean :: [RSSItem] -> [RSSItem]
clean = nubBy $ \x y -> let a = takeWhile (/= ' ') . fromJust $ rssItemTitle x
                            b = takeWhile (/= ' ') . fromJust $ rssItemTitle y
                        in a == b
