import Data.List
import Data.Maybe
import Control.Exception
import Control.Monad
import System.IO

nameTag        = "NAME"
coordinatesTag = "coordinates"
closingBracket = "}"
doubleQuote    = "\""

parse' :: (String, [String]) -> IO (String, [String])
parse' xs = return $ parse'' xs
    where
        parse'' (x,[]) = (x,[])
        parse'' (x,xs) = getCoordinates $ getName (x, xs)

getName :: (String, [String]) -> (String, [String])
getName (x, xs) = getName' (x, findName xs)
    where
        getName' (val, name:state) = (val ++  name' ++ " ", state)
            where
                name' = init. init . tail $ name -- remove quotes and comma
        getName' (val, _)             = (val, [])
        findName xs                    = drop 1 $ dropWhile (not . isNameTag) xs

getCoordinates :: (String, [String]) -> (String, [String])
getCoordinates (x, xs) = (x ++ val' ++ " ", state) 
    where
        (val, state) = getCoord xs
        val'         = concat val
        getCoord xs  = break (isClosingBracket) $ findCoord xs
        findCoord xs = drop 1 $ dropWhile (not . isCoordinateTag) xs

isNameTag :: String -> Bool
isNameTag = isInfixOf nameTag

isCoordinateTag :: String -> Bool
isCoordinateTag = isInfixOf coordinatesTag

isClosingBracket :: String -> Bool
isClosingBracket = isInfixOf closingBracket

getFileSize :: FilePath -> IO (Maybe Integer)
getFileSize path = handle handler
                   $ bracket (openFile path ReadMode) (hClose) (\h -> do size <- hFileSize h
                                                                         return $ Just size)
    where
        handler :: SomeException -> IO (Maybe Integer)
        handler _ = return Nothing

startParse xs = do
    (val, state) <- parse' xs
    if length val > 1000
    then return val
    else startParse (val, state)
    -- case state of
        -- [] -> return val
        -- _  -> startParse (val, state)

main = do
    contents <- readFile "c:\\haskell\\svg\\world.geojson"
    let contents' = words contents
    result <- startParse ("", contents')
    writeFile "c:\\haskell\\svg\\result.txt" result