module Handler.Workflow.Definition.Delete
  ( getAWDDeleteR, postAWDDeleteR
  ) where

import Import

import Handler.Utils.Delete

import qualified Database.Esqueleto as E

import qualified Data.Set as Set


getAWDDeleteR, postAWDDeleteR :: WorkflowScope' -> WorkflowDefinitionName -> Handler Html
getAWDDeleteR = postAWDDeleteR
postAWDDeleteR wds' wdn = do
  wdId <- runDB . getKeyBy404 $ UniqueWorkflowDefinition wdn wds'
  deleteR DeleteRoute
    { drRecords = Set.singleton wdId
    , drGetInfo = \workflowDefinition -> do
        let instanceCount = E.subSelectCount . E.from $ \workflowInstance ->
              E.where_ $ workflowInstance E.^. WorkflowInstanceDefinition E.==. E.just (workflowDefinition E.^. WorkflowDefinitionId)
            workflowCount = E.subSelectCount . E.from $ \(workflowInstance `E.InnerJoin` workflow) -> do
              E.on $ workflow E.^. WorkflowWorkflowInstance E.==. E.just (workflowInstance E.^. WorkflowInstanceId)
              E.where_ $ workflowInstance E.^. WorkflowInstanceDefinition E.==. E.just (workflowDefinition E.^. WorkflowDefinitionId)
        return ( workflowDefinition E.^. WorkflowDefinitionScope
               , workflowDefinition E.^. WorkflowDefinitionName
               , instanceCount, workflowCount
               )
    , drUnjoin = id
    , drRenderRecord = \(E.Value scope, E.Value name, E.Value instanceCount, E.Value workflowCount) ->
        return [whamlet|
          $newline never
          #{name}
          \ (_{scope}
          $if instanceCount > 0
            ; _{MsgWorkflowDefinitionConcreteInstanceCount instanceCount}
          $if workflowCount > 0
            ; _{MsgWorkflowDefinitionConcreteWorkflowCount workflowCount}
          )
        |]
    , drRecordConfirmString  = \(E.Value scope, E.Value name, _, _) ->
        return [st|#{toPathPiece scope}.#{name}|]
    , drCaption = SomeMessage MsgWorkflowDefinitionDeleteQuestion
    , drSuccessMessage = SomeMessage MsgWorkflowDefinitionDeleted
    , drFormMessage = const $ return Nothing
    , drAbort = SomeRoute AdminWorkflowDefinitionListR
    , drSuccess = SomeRoute AdminWorkflowDefinitionListR
    , drDelete = \k cascade -> do
        updateWhere [WorkflowInstanceDefinition ==. Just k] [WorkflowInstanceDefinition =. Nothing]
        cascade
    }
