module Main (main) where

import Text.Parsec hiding (satisfy)
import Text.HTML.TagSoup (parseTags, Tag(TagText), (~==))
import Text.HTML.Download (openURL)
import Data.Char (isDigit)
import Data.List (findIndex)

main =
  do src <- openURL "http://www.haskell.org/haskellwiki/Haskell"
     let x = tagParse counter (parseTags src)
     putStrLn $ "haskell.org has been hit " ++ show x ++ " times"


counter =
  do skipTo (tag "<div class=printfooter>")
     count 2 (skipTo (tag "<p>"))
     s <- tagText ""
     let ss = words s
     case findIndex (== "times.") ss of
       Just i -> let num = ss !! (i - 1)
                 in return (read (filter isDigit num) :: Int)
       Nothing -> parserZero


--
-- tag parser library
--

tagParse p ts =
  either ( error . show ) id $ parse p "tagsoup" ts

tagEater matcher =
  tokenPrim show (\pos t ts -> incSourceLine pos 1) matcher

anyTag = tagEater Just

satisfy f =
  tagEater (\t -> if f t then Just t else Nothing)

tag t = satisfy (~== t) <?> show t

tagText str = do TagText x <- tag (TagText str)
                 return x

skipTo p = try p <|> (anyTag >> skipTo p)

