module Data.TConfig
(
getValue
, repConfig
, readConfig
, writeConfig
, remKey
, addKey
) where
import System.IO
import Data.List
import Data.Char
import qualified Data.Map as M
type Key = String
type Value = String
type Conf = M.Map Key Value
addKey :: Key -> Value -> Conf -> Conf
addKey k v conf = M.insert k (addQuotes v) conf
checkKey :: Key -> Conf -> Bool
checkKey k conf = M.member k conf
remKey :: Key -> Conf -> Conf
remKey k conf = M.delete k conf
getValue :: Key -> Conf -> Maybe Value
getValue k conf = case M.lookup k conf of
Just val -> Just $ stripQuotes val
Nothing -> Nothing
stripQuotes x | any isSpace x = filter (/= '\"') x
| otherwise = x
addQuotes :: String -> String
addQuotes x | any isSpace x = "\"" ++ x ++ "\""
| otherwise = x
repConfig :: Key -> Value -> Conf -> Conf
repConfig k rv conf = let f _ = Just rv
in M.alter f k conf
readConfig :: FilePath -> IO Conf
readConfig path = readFile path >>= return . parseConfig
writeConfig :: FilePath -> Conf -> IO ()
writeConfig path con = writeFile path $ putTogether con
putTogether :: Conf -> String
putTogether = concat . putTogether' . backToString
where putTogether' (x:y:xs) = x : " = " : y : "\n" : putTogether' xs
putTogether' _ = []
backToString :: Conf -> [String]
backToString conf = backToString' $ M.toList conf
where backToString' ((x,y):xs) = x : y : backToString' xs
backToString' _ = []
parseConfig :: String -> Conf
parseConfig = listConfig . popString . parse
parse :: String -> [String]
parse = words . filter (/= '=')
listConfig :: [String] -> Conf
listConfig xs = M.fromList $ helper xs
where helper (x:y:xs) = (x,y) : helper xs
helper _ = []
popString :: [String] -> [String]
popString [] = []
popString (x:xs)
| head x == '\"' = findClose $ break (('\"' ==) . last) xs
| otherwise = x : popString xs
where findClose (y,ys) =
[unwords $ x : y ++ [head ys]] ++ popString (tail ys)