{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}

module KitsuneBook.Settings where

import BasicPrelude hiding (lookup, unlines)
import Configurator
import Data.Text (unlines)
import Filesystem.CanonicalPath as Path

data Settings =
  Settings {workingDirectory :: Text
           ,defaultNoteExtension :: Text

           ,editNoteCommand :: [(Text, Text)]
           ,viewNoteCommand :: [(Text, Text)]

           ,editInfoCommand :: Text
           ,viewInfoCommand :: Text

           ,viewFolderCommand :: Text

            -- list settings
           ,listCountOfNewest :: Int
           ,listCountOfOldest :: Int
           ,listDefaultVersion :: ListType
           ,listSeparator :: Text}

readSettings :: MonadIO m => CanonicalPath -> m (Either Text Settings)
readSettings path = liftIO $
  do config <- load $ Optional path
     wd' <- lookupMandatory config "working-directory"
     case wd' of
       Nothing -> return . Left $ "Please, specify 'working-directory' in " ++ toText' path
       Just wd -> liftM Right $
         Settings wd
         <$> lookupOptional ".md" config "note-extension"
         <*> lookupOptional [("*", "emacs")] config "edit-note-command"
         <*> lookupOptional [("*", "emacs")] config "view-note-command"
         <*> lookupOptional "emacs" config "edit-info-command"
         <*> lookupOptional "emacs" config "view-info-command"
         <*> lookupOptional "emacs" config "view-folder-command"
         <*> lookupOptional 4 config "list-count-of-newest"
         <*> lookupOptional 2 config "list-count-of-oldest"
         <*> (validateListType <$> read <$> lookupOptional "short" config "list-default-version")
         <*> lookupOptional " ..." config "list-separator"

defaultSettings :: Text
defaultSettings = unlines
  ["working-directory = \"~/KitsuneBook\""
  ,"note-extension = \".md\""
  ,"edit-note-command = [[\"*\", \"emacs\"]]"
  ,"view-note-command = [[\"*\", \"emacs\"]]"
  ,"edit-info-command = \"emacs\""
  ,"view-into-command = \"emacs\""
  ,"view-folder-command = \"emacs\""
  ,"list-count-of-newest = 4"
  ,"list-count-of-oldest = 2"
  ,"list-separator = \" ...\""]

data ListType
  = ListShort
  | ListLong
  | ListDefault
  deriving (Eq)

instance Show ListType where
  showsPrec _ ListShort = showString "short"
  showsPrec _ ListLong = showString "long"
  showsPrec _ ListDefault = showString "default"

instance Read ListType where
  readsPrec _ value = tryParse [("short", ListShort), ("long", ListLong), ("default", ListDefault)]
    where tryParse [] = []
          tryParse ((attempt, result):xs) =
            if take (length attempt) value == attempt
            then [(result, drop (length attempt) value)]
            else tryParse xs

validateListType :: ListType -> ListType
validateListType t = if t == ListDefault
                        then ListShort
                        else t

defaultSettingsPath :: IsString a => a
defaultSettingsPath = "~/.kitsunebook.cfg"
