{-
  This module is part of Chatty.
  Copyleft (c) 2014 Marvin Cohrs

  All wrongs reversed. Sharing is an act of love, not crime.
  Please share Antisplice with everyone you like.

  Chatty is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Chatty is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Chatty. If not, see <http://www.gnu.org/licenses/>.
-}

-- | Provides an 'ExtendedPrinter' that handles colours using HTML output.
module Text.Chatty.Extended.HTML where

import Text.Chatty.Printer
import Text.Chatty.Extended.Printer
import Control.Monad.Trans.Class
import Control.Monad.IO.Class

-- | An 'ExtendedPrinter' for HTML output.
newtype HtmlPrinterT m a = HtmlPrinter { runHtmlPrinterT :: m a }

instance Monad m => Monad (HtmlPrinterT m) where
  return = HtmlPrinter . return
  (HtmlPrinter p) >>= f = HtmlPrinter $ do p' <- p; runHtmlPrinterT (f p')

instance MonadTrans HtmlPrinterT where
  lift = HtmlPrinter

instance Functor m => Functor (HtmlPrinterT m) where
  fmap f (HtmlPrinter p) = HtmlPrinter $ fmap f p

instance MonadIO m => MonadIO (HtmlPrinterT m) where
  liftIO = lift . liftIO

instance MonadPrinter m => MonadPrinter (HtmlPrinterT m) where
  mprint = lift . mprint . concatMap maskHtml
  mnoecho = lift . mnoecho . concatMap maskHtml
  mflush = lift mflush

instance MonadPrinter m => ExtendedPrinter (HtmlPrinterT m) where
  estart c =  lift $ mprint $ concat ["<span style=\"color: #", hexColour c, ";\">"]
  efin = lift $ mprint "</span>"

-- | Convert the given character to its HTML representation.
maskHtml :: Char -> String
maskHtml '&' = "&amp;"
maskHtml '<' = "&lt;"
maskHtml '>' = "&gt;"
maskHtml ' ' = "&nbsp;"
maskHtml c = [c]

-- | Convert the given colour to its CSS representation.
hexColour (Dull Green) = "007F00"
hexColour (Vivid Green) = "00FF00"
hexColour (Dull Red) = "7F0000"
hexColour (Vivid Red) = "FF0000"
hexColour (Dull Yellow) = "7F7F00"
hexColour (Vivid Yellow) = "FFFF00"
hexColour (Dull Blue) = "00007F"
hexColour (Vivid Blue) = "0000FF"
hexColour (Dull Black) = "000000"
hexColour (Vivid Black) = "606060"
hexColour (Dull White) = "909090"
hexColour (Vivid White) = "FFFFFF"
hexColour (Dull Cyan) = "007F7F"
hexColour (Vivid Cyan) = "00FFFF"
hexColour (Dull Magenta) = "7F007F"
hexColour (Vivid Magenta) = "FF00FF"