module Beekeeper.System.Parse where

import Prelude hiding (catch)

import Control.Exception (catch, IOException)

import qualified Language.Python.Version2.Parser as Python2
import qualified Language.Python.Common.AST as Py

import System.IO (hGetContents,
                  hPutStrLn,
                  stderr,
                  withFile,
                  IOMode(..))
import System.Process (readProcess)

currHax, pyxlPath :: String
currHax = "/home/sujayakar/dbdev/srv/server/"
pyxlPath = "/home/sujayakar/pyxl_hax/dropbox/pyxl/scripts/parse_file.py"

parseFile :: FilePath -> IO Py.ModuleSpan
parseFile path = withFile path ReadMode parseHandle
  where parseHandle handle = do
          contents <- hGetContents handle
          case Python2.parseModule contents path of
            Left _ -> parsePyxl path
            Right (val, _) -> return val

-- Opening up a subprocess to parse Pyxl is too slow for now
parsePyxl :: FilePath -> IO Py.ModuleSpan
parsePyxl path = do
  putStr $ "pyxl parsing " ++ drop (length currHax) path ++ "..."

  let handler :: IOException -> IO String
      handler _ = putStrLn "failed pyxl" >> return ""
      parser = do
        contents <- readProcess pyxlPath [path] ""
        putStrLn "done"
        return contents

  contents <- catch parser handler

  case Python2.parseModule contents path of
    Left _ -> do
      hPutStrLn stderr ("failed parse: " ++ drop (length currHax) path)
      return (Py.Module [])
    Right (val, _) -> return val