{- DisTract ------------------------------------------------------\
 |                                                                 |
 | Copyright (c) 2007, Matthew Sackman (matthew@wellquite.org)     |
 |                                                                 |
 | DisTract is freely distributable under the terms of a 3-Clause  |
 | BSD-style license. For details, see the DisTract web site:      |
 |   http://distract.wellquite.org/                                |
 |                                                                 |
 \-----------------------------------------------------------------}

{-# LANGUAGE TemplateHaskell #-}

module DisTract.HTML.BugNew
    (formatNew,
     newToHTML
    )
where

import Text.HTML.Chunks
import DisTract.Types
import DisTract.Utils
import DisTract.Layout
import DisTract.HTML.Fields
import System.FilePath
import Data.List
import Data.Time
import qualified Data.Map as M

$(chunksFromFile "./html/templates/bugNew.html")

formatNew :: Config -> IO ()
formatNew config
    = do { htmlStr <- newToHTML config
         ; writeFile path htmlStr
         }
    where
      path = combine (htmlDir . baseDir $ config) filename
      filename = addExtension "newBug" "html"


newToHTML :: Config -> IO String
newToHTML config
    = do { time <- (getZonedTime >>= formatTimeHuman)
         ; let page = format $ Chunk_page
                      { page_base = baseDir config,
                        page_fields = "<tr>\n" ++ fieldsFormatted ++ "</tr>\n",
                        page_generation_time = time,
                        page_version = version
                      }
         ; return page
         }
    where
      version = (packageName config) ++ " version " ++ (packageVersion config)
      fieldsSorted = sort . filter (not . isPseudoField) . M.elems .
                      fieldDfns $ config
      fieldsFormattedList = map (toFormInput . fieldDefault) fieldsSorted
      fieldsFormatted = concat . intersperseEvery 2 "</tr><tr>\n" .
                        filter (not . null) $ fieldsFormattedList