module Handler.Home where

import Import
import Yesod.Form.Bootstrap3
import Yesod.Text.Markdown

blurbForm :: Maybe Blurb -> AForm Handler Blurb
blurbForm mblurb = Blurb
                   <$> areq markdownField (bfs ("Blurb" :: Text)) (blurbBlurb <$> mblurb)
                   <*> areq markdownField (bfs ("Social" :: Text)) (blurbSocial <$> mblurb)

getHomeR :: Handler Html
getHomeR = do
    uid <- maybeAuthId
    (widget, enctype) <- generateFormPost . renderBootstrap3 BootstrapBasicForm $ blurbForm Nothing
    currentPost <- runDB $ selectFirst [] [Desc BlogId]
    currentBlurb <- runDB $ selectFirst [] [Desc BlurbId]
    defaultLayout $ do
        setTitle "I like when it works | The adventures of a programming autodidact"
        addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"
        addScriptRemote "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/highlight.min.js"
        addScriptRemote "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/collapse.js"
        addStylesheetRemote "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/styles/zenburn.min.css"
        $(widgetFile "homepage")

postHomeR :: Handler Html
postHomeR = do
    uid <- maybeAuthId
    ((res, widget), enctype) <- runFormPost . renderBootstrap3 BootstrapBasicForm $ blurbForm Nothing
    currentPost <- runDB $ selectFirst [] [Desc BlogId]
    currentBlurb <- runDB $ selectFirst [] [Desc BlurbId]
    case res of
        FormSuccess blurb -> do
            _ <- runDB $ insert blurb
            redirect $ HomeR
        _ -> defaultLayout $(widgetFile "homepage")
