module Stats where
import Database
import Control.Monad.IO.Class

data Query = Query String

getAvg =  makeQuery "select avg(time), Subject from todo  group by Subject order by avg(time) desc"

getSum =  makeQuery "select sum(time), Subject from todo group by Subject order by sum(time) desc"

makeRow x =  "<tr> <th>" ++ (x !! 0) ++ "</th> <th>  " ++ (x!! 1) ++ "</th> </tr>"

makeTable stats = "<table style='width:100%'>" ++ (mconcat (map  makeRow stats)) ++ "</table>"


genStats = getSubjects >>= mapM makeGithub >>= \gits -> getAvg >>=
  \avg -> getSum >>= \sum -> return (hea ++ (makeTable avg) ++ "</br> <h1> Sum </h1>" ++ (makeTable sum) ++ "</html>" ++ (mconcat gits))

hea :: String
hea = "<!DOCTYPE html> <html> <script src='/js-chart-widgets.min.js'></script><h1> avg </h1>"

makeGithub :: String -> IO String
makeGithub subject = do
  z <-   makeQuery ("select Due from todo where subject = '" ++ subject ++ "' and state = 0")
  let head = "<h2 id='"++ subject ++ "'> Calendar "++ subject ++ " </h2> <script> new Calendar({ append_to: '" ++ subject ++ "',num_weeks: 51,day_size: 11, data: ["
  let q = Prelude.map (\x -> "['" ++ (x !! 0) ++"',500],") z
  let bot = "  ], color: '#005500' }); </script>"
  return (head ++ (Prelude.concat q )++  bot)