module Main (
  main
) where

import Control.Monad (mapM_)
import System.Environment (getArgs)

import Language.Py.ParseError (ParseError(..))
import Language.Py.SrcLocation (SrcSpan(..), getSpan)
import Language.Py.Parser (parseModule)

import PyHint.Scanner (scanModule)
import PyHint.Files (getPythonFiles, getFixedContent)
import PyHint.Message (Message(..))

getErrorMessage :: ParseError -> Message
getErrorMessage (UnexpectedToken token) = Message "E000" "Syntax error: unexpected token" (getSpan token)
getErrorMessage (UnexpectedChar _ sloc) = Message "E000" "Syntax error: unexpected char" (getSpan sloc)
getErrorMessage (StrError _) = Message "E000" "Syntax error" SpanEmpty

scanFile :: String -> IO ()
scanFile file = do
  content <- getFixedContent file
  case parseModule content file of
    Left e -> printMessage file (getErrorMessage e)
    Right (m, _) -> mapM_ (printMessage file) (scanModule m)

printMessage :: String -> Message -> IO ()
printMessage filename (Message t msg span) = case span of
  SpanCoLinear _ r c _ -> print filename r c
  SpanMultiLine _ r c _ _ -> print filename r c
  SpanPoint _ r c -> print filename r c
  SpanEmpty -> print filename 0 0
  where print f r c = putStrLn $ f ++ ":" ++ show r ++ ":" ++ show c ++ ": " ++ t ++ " " ++ msg

main = do
  topdir <- fmap head getArgs
  files <- getPythonFiles topdir
  mapM_ scanFile files
