
module Main
where

import System.IO
import System.Process
import System.Environment
import Text.Regex
import Data.Maybe
import Debug.Trace

basedir = "dist/hscomplete"
logfile = basedir ++ "/log"
inputfile = basedir ++ "/haskell.hs"
outputfile = basedir ++ "/results"
hssourcedir = "src"
packagename = "tmp"
hooglepackages = "+base +directory +process"

main :: IO ()
main = withFile logfile WriteMode complete

complete :: Handle -> IO ()
complete log = do
  hPutStrLn log "log"
  [line', col', base] <- getArgs
  let line = read line' :: Int
  let col = read col' :: Int
  hPutStrLn log $ show line ++ ":" ++ show col ++ ":" ++ base
  content <- fmap (fixContent line col) $ readFile inputfile
  writeFile (basedir ++ "/main.hs") content
  (ec, _, stderr) <- readProcessWithExitCode "ghc" ["--make", basedir ++ "/main.hs", "-i" ++ hssourcedir] []
  hPutStr log stderr
  let re1 = mkRegex "Couldn't match expected type `([^']*)'"
  let re2 = mkRegex "against inferred type `\\(\\)'"
  let m1 = matchRegex re1 stderr
  let m2 = matchRegex re2 stderr
  hPutStrLn log $ "match: " ++ show m1 ++ " " ++ show m2
  if isJust m1 && isJust m2 && length (fromJust m1) == 1
    then do
      (ec, stdout, _) <- readProcessWithExitCode "hoogle" (hoogleOpts ++ [base ++ " :: " ++ (head $ fromJust m1)]) []
      let ls = map (head . drop 1 . take 2 . words) $ lines stdout
      hPutStrLn log (show ls)
      hPutStrLn log $ show (filter (filterBase base) ls)
      withFile outputfile WriteMode (\h -> mapM_ (hPutStrLn h) $ filter (filterBase base) ls)
    else writeFile outputfile ""
  hPutStrLn log "OK"

hoogleOpts = ["--data=dist/doc/html/" ++ packagename ++ "/" ++ packagename ++ ".hoo"] ++ [hooglepackages]

--XXX
fixContent :: Int -> Int -> String -> String
fixContent line col cont = trace (show ln) $ concat $ map (++ "\n") $ pre ++ post
  where
  ls = lines cont
  pre = take (line - 1) ls ++ [ln']
  post = tail post'
  post' = drop (line - 1) ls
  ln = head post'
  ln' = take (col - 1) ln ++ "() " ++ drop col ln

filterBase :: String -> String -> Bool
filterBase base str = ls > lb && str' == base
  where
  lb = length base
  ls = length str
  str' = take lb str

