module Grakn.Query
  ( IsQuery(queryString)
  , Match
  , GetQuery
  , match
  , get
  , limit
  ) where

import           Grakn.Pattern  (Pattern)
import           Grakn.Property (Var)
import           Grakn.Util     (Convert, commas, convert, spaces)

class IsQuery q where
  queryString :: q -> String

-- |A Graql 'match' part that finds a pattern in the knowledge base
data Match
  = Match [Pattern]
  | Limit Match
          Integer

data GetQuery =
  GetQuery Match
           [Var]

-- |Create a match by providing a list of patterns
match :: Convert a Pattern => [a] -> Match
match = Match . map convert

-- |Get variables from a match, intended to be used infix
get :: [Var] -> Match -> GetQuery
get = flip GetQuery

-- |Limit a match, intended to be used infix
limit :: Integer -> Match -> Match
limit = flip Limit

instance Show Match where
  show (Match patts)  = "match " ++ spaces patts
  show (Limit mq lim) = show mq ++ " limit " ++ show lim ++ ";"

instance Show GetQuery where
  show (GetQuery match_ [])   = show match_ ++ " get;"
  show (GetQuery match_ vars) = show match_ ++ " get " ++ commas vars ++ ";"

instance IsQuery GetQuery where
  queryString = show

instance IsQuery String where
  queryString = id