--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- |
--Module       : Email
--Author       : Joe Fredette
--License      : BSD3
--Copyright    : Joe Fredette
--
--Maintainer   : Joe Fredette <jfredett.at.gmail.dot.com>
--Stability    : Unstable
--Portability  : Portable
--
--------------------------------------------------------------------------------
--Description  : Email Data type, parsing functions, helper functions.  
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

module HackMail.Data.Email ( module HackMail.Data.ParseEmail
                           , module HackMail.Control.Checksum
                           , writeEmail
                           , emailChecksum 
                           , grabTokValUnsafe, grabTokVal
                           ) where

import HackMail.Data.ParseEmail
import HackMail.Control.Checksum
import System.IO
import System.Directory


writeEmail :: Email -> FilePath -> FilePath -> IO ()
writeEmail e dirPath msgPath = do
        createDirectoryIfMissing True dirPath
        writeFile msgPath (show e) 

emailChecksum :: Email -> String
emailChecksum e = checksum . show $ e

grabTokValUnsafe :: Email -> HeaderTok -> String
grabTokValUnsafe (Email h _) htok = findTok h htok
        where   findTok STOP _ = ""
                findTok (HDR h1 s hdrNext) hgvn = if (h1 == hgvn) then s else (findTok hdrNext hgvn)

grabTokVal :: Email -> HeaderTok -> Maybe String
grabTokVal e htok 
        | unsafe == ""  = Nothing
        | otherwise     = Just unsafe
        where unsafe = grabTokValUnsafe e htok