module Main where

import CounterState

import Control.Monad
import Control.Monad.Trans
import Data.Monoid

import Happstack.Data.Proxy
import Happstack.Helpers
import Happstack.Server
import Happstack.Server.Helpers
import Happstack.State.Transaction

import Text.StringTemplate
import Text.StringTemplate.Helpers

{-
   Starts the "smart" server on localhost:8080.  Runs the Happstack webserver
   and is responsible for the MACID persistence.

   This example stores an Integer value that is incremented when either the 
   /macid1 or /macid2 URLs are loaded.  It is persisted in the "_local" 
   directory under the running executable.  To reinitialize the state value 
   to "0", simply delete this directory before restarting the executable.

   smartserver ::  (Methods st, Component st, ToMessage a) => 
      Conf -> String -> ServerPartT IO a -> Proxy st -> IO ()
-}
main :: IO ()
main = do
   putStrLn "starting smart server ...."
   smartserver (Conf 8080 Nothing) "happs-example" (simpleHandlers `mappend`
      handlerUsingMACID `mappend` handlerUsingMACIDAndHST) stateProxy


{-
   Create a Proxy to hold the application state.  The Proxy type has no 
   actual data of its own.  The smartserver requires the proxy to start 
   the Happs state system.
-}
stateProxy :: Proxy CounterState
stateProxy = Proxy


{-
   Simple handlers for static html responses
-}
simpleHandlers :: ServerPartT IO Response
simpleHandlers = msum 
   [  exactdir "/simple1" ( return . toResponse $ "Simple handler example 1" )
   ,  exactdir "/simple2" ( return . toResponse . HtmlString $ "<H1>Simple handler example 2</H1>") ]


{-
   Handler with dynamic content which updates and displays state
-}
handlerUsingMACID :: ServerPartT IO Response
handlerUsingMACID = 
   exactdir "/macid1" $
      liftIO $ do
         count <- newCount
         return . toResponse . HtmlString $ ( "Current count is: " ++ show count )


{-
   Handler with dynamic content created using HST template to prepare the response
-}
handlerUsingMACIDAndHST :: ServerPartT IO Response
handlerUsingMACIDAndHST = 
   exactdir "/macid2" $
      liftIO $ do
         templates <- directoryGroup "templates"
         count <- newCount
         let response = renderTemplateGroup templates [("count", count)] "counter"
         return . toResponse . HtmlString $ response


{-
   Increments the counter state 
-}
newCount :: (MonadIO m) => m Int
newCount =  liftIO $ do
   update IncCount
   query GetCount

