{-# LANGUAGE GADTs             #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes        #-}
{-# LANGUAGE ScopedTypeVariables #-}

module HypeStat where

import           Data.ByteString
import           Data.Vector     as V
import           HypeStat.Model
import           HypeStat.Repr   as R
import           HypeStat.Valve as HSV

groupToDoc :: (Foldable t, Applicative t) => HSV.Group Document Document -> t Document
groupToDoc = undefined

valvify :: forall t col p. (Foldable t, Applicative t, Monoid (t Document), col ~ t Document) => SPipeline -> Valve p col col
valvify = V.foldl1' (|=>) . V.map _valvify
  where
    _valvify :: SOp -> Valve p col col
    _valvify (MatchOp dct) = HSV.match (mkMatchFunc dct)
    _valvify (ProjectOp dct) = HSV.project (mkProjectFunc dct)
    _valvify (GroupOp key val) = HSV.groupBy (mkGroupFunc key) |=> HSV.Valve groupToDoc |=> HSV.project (mkProjectFunc val)
    _valvify _ = error "Not implemented yet"

mkGroupFunc :: Dict -> Document -> Document
mkGroupFunc _ = undefined

mkProjectFunc :: Dict -> Document -> Document
mkProjectFunc _ = undefined

mkMatchFunc :: Dict -> Document -> Bool
mkMatchFunc _ = undefined

eitherExec :: (Foldable t, Applicative t, Monoid (t Document), col ~ t Document) => ByteString -> col -> Either String col
eitherExec bs = case parseRepr bs of
  Left err -> const (Left err)
  Right pl -> Right . runValve (valvify pl)

maybeExec :: (Foldable t, Applicative t, Monoid (t Document), col ~ t Document) => ByteString -> col -> Maybe col
maybeExec bs = case parseRepr bs of
  Left _ -> const Nothing
  Right pl -> Just . runValve (valvify pl)
