--------------------------------------------------------------------
-- |
-- Module    : Generate sparkline graphs of hackage uploads
-- Copyright : (c) Don Stewart 2008-2011
-- License   : BSD3
--
-- Maintainer: Don Stewart <dons00@gmail.com>
-- Stability : stable
-- Portability:
--
--------------------------------------------------------------------

import Data.List
import Data.Maybe
import Graphics.Rendering.HSparklines
import System.Directory
import System.FilePath
import System.Locale
import System.Time
import System.Time.Parse
import Network.Download
import qualified Data.ByteString.Char8 as C

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

png1 = "hackage-monthly.png"
png2 = "hackage-daily.png"
png3 = "hackage-all.png"

graph = barSpark -- { bgColor = rgb 0xEE 0xEE 0xEE }

main :: IO ()
main = do
    pwd <- getCurrentDirectory
    e   <- openURI url
    case e of
        Left  err  -> error $ "Failed to download: " ++ show err
        Right bsrc -> do {

    ; let src = C.unpack bsrc

    ; let dates = catMaybes . sort . map parse . lines $ src

    ; let today     = last dates
          permonth  = groupBy month dates
          thismonth = groupBy day . filter (month today) $ dates
          monthlies = map genericLength permonth
          dailies   = map genericLength thismonth
          alls      = reverse. take 90 . reverse $ map genericLength (groupBy (\a b -> month a b && day a b) dates)
          top       = maximum monthlies

    ; graph1 <- make (graph { limits = (0,round top) })  monthlies
    ; graph2 <- make (graph { limits = (0,20) }) dailies
    ; graph3 <- make (graph { limits = (0,20) }) alls

    ; savePngFile png1 graph1
    ; savePngFile png2 graph2
    ; savePngFile png3 graph3

    ; putStrLn $ "Wrote: " ++ pwd </> png1
    ; putStrLn $ "Wrote: " ++ pwd </> png2
    ; putStrLn $ "Wrote: " ++ pwd </> png3
    }

  where
    parse = parseCalendarTime defaultTimeLocale "%c"
    month a b = ctYear a == ctYear b && ctMonth a == ctMonth b
    day   a b = month a b && ctDay a == ctDay b
