module HPasteAdmin (adminSubsystem, loadAccounts, Accounts()) where

import Control.Exception
import Control.Monad.State
import qualified Data.Map as M
import Prelude hiding (catch)

import PasteState
import HtmlPages

import HAppS

newtype Accounts = Accounts (M.Map String String)

loadAccounts :: IO Accounts
loadAccounts = liftM Accounts $
  handle (const . return $ M.empty) $ do
  ls <- liftM lines $ readFile "accounts.txt"
  return $ M.fromList [(a,b) | [a,b] <- map words ls]
  
---------------------------------------------------------------------

adminSubsystem :: Monad m
               => Accounts
               -> ServerPart (Ev PasteState Request) Request m Result
adminSubsystem (Accounts accounts)
  = multiIf (Prefix ["admin"]) [GET,POST]
      [hs ()                ()   $ basicAuth "Admins Only" accounts
      ,h ["admin","delete"] GET  $ ok       (val $ adminDeletePage "")
      ,h ["admin","delete"] POST $ ok       handlePostDelete
      ,h ()                 ()   $ ok       (val adminIndexPage)
      ]

---------------------------------------------------------------------

handlePostDelete :: () -> Request -> Paste
handlePostDelete () rq = do
  pasteId <- lookMb readM rq "pasteId"
  boundId <- currentId
  if pasteId < boundId && pasteId > 0
    then do
      deleteEntry pasteId
      respond $ adminDeletePage $ "Deleted paste " ++ show pasteId
    else
      respond $ adminDeletePage "Bad Paste ID"
