module Main (main) where

import Search(rabinKarpMain)
import GridReader(createGridFromInput)


import System.Environment ( getArgs )
import System.Exit ( die )
import Control.Monad ( when)
import qualified Data.ByteString as S
import Data.ByteString.Char8 as C8 (pack)
import Data.Char (toUpper, isAlpha)



main :: IO ()
main = do
  args <- getArgs
  case args of
    [patt, nVal, filename] -> do
      let n = (read nVal :: Int)
      let m = length patt

      when(m < 2) $
        die "Pattern must be of length >= 2"

      when(m > n) $
        die "Pattern length must be less than or equal to grid size"

      when (False `elem` map isAlpha patt) $
        die "Only alphabets supported in input"

      let pattUpp = map toUpper patt
      contents <- S.readFile filename

      let text = createGridFromInput contents n
      let pattern =  (S.unpack . C8.pack) pattUpp
      let rev_pattern = (S.unpack . C8.pack) (reverse pattUpp)

      let rowmatches = map (rabinKarpMain pattern rev_pattern text m n True)
                          [0..n-1]
      let colmatches = map (rabinKarpMain pattern rev_pattern text m n False)
                         [0..n-1]
      let filteredRowMatches = concat $ filter (not . null) rowmatches
      let filteredColMatches = concat $ filter (not . null) colmatches
      if not (null filteredRowMatches) then do
        print "Row matches found at coordinates:"
        sequence_ [print w | w <- filteredRowMatches]
      else do
        print "Pattern not found across row"
      if not (null filteredColMatches) then do
        print "Column matches found at coordinates:"
        sequence_ [print w | w <- filteredColMatches]
      else do
        print "Pattern not found across column"
    _ -> die "Usage: stack exec -- word-search-seq-exe <pattern> <grid_size> <file_containing_grid>"

