module XMonadContrib.StatusBar
    (SBConf(..),
     defaultSBConf,
     statusBar) where

import Data.List (genericLength, genericReplicate, inits)
import Data.IORef
import System.IO (Handle, BufferMode(..), hPutStrLn, hSetBuffering)
import System.IO.Unsafe (unsafePerformIO)
import System.Process (ProcessHandle, runInteractiveProcess)

import Graphics.X11.Xlib (Rectangle(..), Dimension, Position)
import qualified StackSet as W
import XMonad
import XMonadContrib.DynamicLog (pprWindowSet)
import XMonadContrib.NamedWindows

data SBConf = SBConf {
      sbDzenFile :: FilePath,
      sbBackgroundColour :: String,
      sbForegroundColour :: String,
      sbInactiveTabBgColour :: String,
      sbInactiveTabFgColour :: String,
      sbActiveTabBgColour :: String,
      sbActiveTabFgColour :: String,
      sbX :: Position,
      sbY :: Position,
      sbWidth :: Dimension,
      sbFont :: String
    }

defaultSBConf :: SBConf
defaultSBConf =
    SBConf { sbDzenFile = "dzen2"
                    , sbBackgroundColour = "black"
                    , sbForegroundColour = "white"
                    , sbInactiveTabBgColour = "grey40"
                    , sbInactiveTabFgColour = "grey80"
                    , sbActiveTabBgColour = "grey80"
                    , sbActiveTabFgColour = "grey20"
                    , sbX = 0
                    , sbY = 0
                    , sbWidth = 0
                    , sbFont = "fixed"
                    }

statusBar :: SBConf -> X ()
statusBar c = do
  ac <- adaptToScreen c
  maybeProcess <- io $ readIORef dzenProcess
  (_, stdin) <- case maybeProcess of
                  (Just process) -> return process
                  Nothing -> io $ do
                    process <- createDzenProcess ac
                    writeIORef dzenProcess (Just process)
                    return process
  s <- barString ac
  io $ hPutStrLn stdin s

adaptToScreen :: SBConf -> X SBConf
adaptToScreen c =
    withWindowSet $ \ws -> do
      let sd = W.screenDetail (W.current ws)
          Rectangle _ _ width height = screenRect sd
      return $ c { sbX     = if sbX c < 0 then (fromIntegral width) + sbX c  else sbX c
                 , sbY     = if sbY c < 0 then (fromIntegral height) + sbY c else sbY c
                 , sbWidth = if sbWidth c <= 0 then width + sbWidth c else sbWidth c
                 }

dzenProcess :: IORef (Maybe (ProcessHandle, Handle))
{- NOINLINE dzenProcess -}
dzenProcess = unsafePerformIO (newIORef Nothing)

createDzenProcess :: SBConf -> IO (ProcessHandle, Handle)
createDzenProcess c = do
  (stdin, _, _, p) <-
      runInteractiveProcess (sbDzenFile c)
                            ["-bg", sbBackgroundColour c,
                             "-fg", sbForegroundColour c,
                             "-x",  show (sbX c),
                             "-y",  show (sbY c),
                             "-w",  show (sbWidth c),
                             "-fn", sbFont c,
                             "-ta", "l"]
                            Nothing
                            Nothing
  hSetBuffering stdin LineBuffering
  return (p, stdin)

barString :: SBConf -> X String
barString c = withWindowSet $ \ws -> do
  let tags = pprWindowSet ws ++ ": "
  titles <- titleString c ((sbWidth c) - approxTextWidth tags) ws
  return $ tags ++ titles

titleString :: SBConf -> Dimension -> WindowSet -> X String
titleString c availableWidth ws =
  case W.stack . W.workspace . W.current $ ws of
    Just s -> do
      let ups = W.up s
          focus = W.focus s
          downs = W.down s
          maxTitleWidth = availableWidth `div`
                          (sum . map genericLength $ [ups, [focus], downs])
          getNameStr w = getName w >>=
                         return .
                         centre (maxTitleWidth `div` approxTextWidth " ") .
                         shrinkWhile shrinkTextWithEllipsis
                                     ((> maxTitleWidth) . approxTextWidth) .
                         show
      upNames   <- mapM getNameStr ups
      focusName <-      getNameStr focus
      downNames <- mapM getNameStr downs
      return $ unwords $
             map (withDzenColours (sbInactiveTabFgColour c) (sbInactiveTabBgColour c)) (reverse upNames) ++
             [withDzenColours (sbActiveTabFgColour c) (sbActiveTabBgColour c) focusName] ++
             map (withDzenColours (sbInactiveTabFgColour c) (sbInactiveTabBgColour c)) downNames
    Nothing -> return ""

approxTextWidth :: String -> Dimension
approxTextWidth = (* 8) . genericLength

type Shrinker = String -> [String]

shrinkTextWithEllipsis :: Shrinker
shrinkTextWithEllipsis cs = cs : (map (++"...") . drop 4 . reverse . inits $ cs)

shrinkWhile :: Shrinker -> (String -> Bool) -> String -> String
shrinkWhile sh p x = sw $ sh x
    where sw [n] = n
          sw [] = ""
          sw (n:ns) | p n = sw ns
                    | otherwise = n

centre :: (Integral i) => i -> String -> String
centre n s = genericReplicate left ' ' ++ s ++ genericReplicate right ' '
    where l     = genericLength s
          left  = max 0 $ (n - l) `div` 2
          right = max 0 $ n - left - l

withDzenColours :: String -> String -> String -> String
withDzenColours fg bg str = "^fg("++fg++")^bg("++bg++")"++str++"^bg()^fg()"
