module System.Taffybar.Widget.Generic.Icon
  ( iconImageWidgetNew
  , pollingIconImageWidgetNew
  ) where
import Control.Concurrent ( forkIO, threadDelay )
import Control.Exception as E
import Control.Monad ( forever )
import Graphics.UI.Gtk
iconImageWidgetNew :: FilePath -> IO Widget
iconImageWidgetNew path = imageNewFromFile path >>= putInBox
pollingIconImageWidgetNew
  :: FilePath 
  -> Double 
  -> IO FilePath 
  -> IO Widget
pollingIconImageWidgetNew path interval cmd = do
  icon <- imageNewFromFile path
  _ <- on icon realize $ do
    _ <- forkIO $ forever $ do
      let tryUpdate = do
            str <- cmd
            postGUIAsync $ imageSetFromFile icon str
      E.catch tryUpdate ignoreIOException
      threadDelay $ floor (interval * 1000000)
    return ()
  putInBox icon
putInBox :: WidgetClass child => child -> IO Widget
putInBox icon = do
  box <- hBoxNew False 0
  boxPackStart box icon PackNatural 0
  widgetShowAll box
  return $ toWidget box
ignoreIOException :: IOException -> IO ()
ignoreIOException _ = return ()