{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import Control.Arrow
import Control.Monad
import Control.Category
import Control.Category.Dual

import Prelude hiding ((.), id)

import FRP.Yampa

import Data.IORef
import Data.Time.Clock
import qualified Data.Set as S
import Data.Functor.Contravariant

import Test.QuickCheck

-- a sort in spec
data Nat = Zero | Suc Nat | Pred Nat deriving (Show, Eq)

-- abstracted signature
data Sign a = Sign a deriving (Show)

-- sorts can be parametric in the signature  
spec0 :: Sign (Nat -> Nat)
spec0 = Sign Suc

-- as can be a logic
spec0' :: Sign (a -> Either a b)
spec0' = Sign Left -- disjunction, co-product

-- we'll reserve logics for operations on categories, not in categories

-- signature type endofunctor
mapSign :: (a -> b) -> Sign a -> Sign b
mapSign f (Sign x) = Sign (f x)

-- arrow review
-- arrows are computations
r0 :: (Arrow a, Category a) => a Nat Nat
r0 = arr Suc -- non-evalated computation  
-- evaluate r0 Zero, result Suc Zero

-- evaluates the first component in its arg
r0' :: (Nat, Nat)
r0' = first (arr Suc) (Zero, (Suc Zero)) -- (Suc Zero, Suc Zero)

-- arrows are categories
-- (b -> c) is the morphism
-- b and c are objects
-- a is the name of the category

-- category of natural numbers
c0 :: (Arrow cat, Category cat) => cat Nat Nat
c0 = arr Suc 

-- proofs of cat props

-- identity
prop_id_0 :: Nat -> Bool
prop_id_0 xs = (id . Suc) xs == (Suc . id) xs

-- associativity (degenerate)
prop_assoc_0 :: Nat -> Bool
prop_assoc_0 xs = ((Suc . Suc) . Suc) xs == (Suc . (Suc . Suc)) xs

-- evaluate
c0' :: Nat
c0' = arr Suc $ Zero -- Suc Zero

-- end arrow review

-- mapSign is an arrow in the type endofunctor category Sign (aka sig) whose objects are signatures 
s0 :: (Arrow sig, Category sig) => sig (a1 -> b) (Sign a1 -> Sign b)
s0 = arr mapSign -- sig is the category Sign, abstract with Signatures as objects

-- omit Category constraint, except where explicit

s0' :: Sign Nat -> Sign Nat
s0' = arr mapSign $ Suc

-- evaluate
s0'' = (arr mapSign $ Suc) (Sign Zero) -- Sign (Suc Zero)

-- prove identity property of type endofunctor category Sign
prop_id_1 :: Eq (Sign a -> Sign b) => (a -> b) -> Bool
prop_id_1 xs = (id . mapSign) xs == (mapSign . id) xs

-- prove associativity property of type endofunctor category Sign
prop_assoc_1 :: Eq (Sign (Sign a) -> Sign (Sign b)) => (a -> b) -> Bool
prop_assoc_1 xs = ((id . mapSign) . mapSign) xs == (mapSign . (mapSign . id)) xs

-- category and arrow combinators provide operations like composition on categories
prop_cat_comp_0 :: Eq (Sign a -> Sign b) => (a -> b) -> Bool
prop_cat_comp_0 xs = (arr id >>> arr mapSign) xs ==  (arr mapSign <<< arr id) xs

-- constructions on categories

--- composition of categories implies product category
p0 :: Arrow cat => cat (a -> b) (Sign (Sign a) -> Sign (Sign b))
p0 = (arr mapSign) >>> (arr mapSign) -- left to right composition

p0' = p0 Suc $ Sign (Sign Zero) -- Sign (Sign (Suc Zero))

-- disjunction ?

-- more institution semantics
-- recall an institution is I <Sign, Sen, Mod>
-- we have Sign
-- Sen : Sign -> Set
-- Mod : Sign^op -> Set
-- Sat : (|=_Sign) Mod Sen
-- ? latex, literate
 
-- rather than mapSet similar to mapSign, use fmap and a combinator from Set as the arrow in the type endofunctor category Set (set) 
se0 :: (Functor f, Arrow set, Category set) => set (f a1) (f (S.Set a1))
se0 = arr (fmap S.singleton)

se0' :: Nat -> S.Set Nat
se0' = arr (fmap S.singleton) Suc

se0'' :: S.Set Nat
se0'' = se0' Zero

-- other set combinators with fmap

-- more proofs

-- sentences Sen : Sign -> Set, composition on the categories Sign and Set is the equivalent of function evaluation in the goguen paper
sen0 :: (Arrow sen, Category sen) => sen (a -> b) (Sign a -> S.Set (Sign b))
sen0 = arr mapSign >>> arr (fmap S.singleton)

-- models Mod : Sign^Op -> Set, compose Dual of sig and set
-- note: dual switched the component order, so I manually switched the name of the type variable to show the arrow reversed
mod0 :: (Arrow mod, Arrow (Dual mod), Category mod) => Dual mod (Sign b -> Sign a) (b -> S.Set a)
mod0 = (Dual $ arr mapSign) >>> arr (fmap S.singleton)

-- proof : composition and function evaluation, see compos-1, given (f . g) if we switch the direction of the arrows, then we must switch the order or the arguments. if we switch the order of the arguments, then we reverse direction of the arrows.

-- evaluate, sen and mod
sen0' :: S.Set (Sign Nat)
sen0' = (arr mapSign >>> arr (fmap S.singleton) $ Suc) (Sign Zero) -- fromList [Sign (Suc Zero)]

mod0' :: S.Set (Sign Nat)
mod0' = (arr (runDual (Dual $ arr mapSign)) >>> arr (fmap S.singleton) $ Pred) (Sign (Suc Zero)) -- fromList [Sign (Suc Zero)]

-- satisfaction
-- what signature satisfies mod and sen under signature morphism

-- satisfaction is the witness to the composition of mod and sen, the result component is now the set of signatures parameterized by sets of ... the sorts in the spec (aka Nat)
-- note : dual switches component order, so I manually reversed the type variable names
sat0 :: (Arrow sat, Arrow (Dual sat), Category sat) => Dual sat (Sign b -> Sign a) (Sign b -> S.Set (Sign (S.Set a)))
sat0 = ((Dual $ arr mapSign) >>> arr (fmap S.singleton)) >>> (arr mapSign >>> arr (fmap S.singleton))

-- evaluate, the witness (Pred . Suc) (Sign (Sign Zero)) "satisfies the constructive proof"
sat0' :: S.Set (Sign (S.Set (Sign Nat)))
sat0' = ((arr (runDual (Dual $ arr mapSign)) >>> arr (fmap S.singleton)) >>> (arr mapSign >>> arr (fmap S.singleton)) $ (Pred . Suc)) (Sign (Sign Zero)) -- fromList [Sign (fromList [Sign (Pred (Suc Zero))])]

-- it would be nice to do something with institutions
-- arrows and reactive programming seem to go back to 2000 or so
-- we can simulate change in institutions with reactimate
-- hence we have "reactive institutions"

type Input = (S.Set (Sign (S.Set (Sign Nat))), DTime)
type Output = Maybe (S.Set (Sign (S.Set (Sign Nat))))

data Stopwatch = Stopwatch { zero :: UTCTime
                           , prev :: UTCTime 
                           }

-- hmm zero and previous are same value
startWatch :: UTCTime -> Stopwatch
startWatch now = Stopwatch now now

-- gets an io ref to started watch at time executed, zero and prev still same
storeWatch :: IO (IORef Stopwatch)
storeWatch = getCurrentTime >>= (newIORef . startWatch)

-- time diff pair (delta, elapsed)
diffTimes :: IORef Stopwatch -> IO (DTime, DTime)
diffTimes ref = do
  now <- getCurrentTime
  (Stopwatch zero prev) <- readIORef ref -- read stored watch
  writeIORef ref (Stopwatch zero now) -- store "now" time 
  let dt = realToFrac (diffUTCTime now prev) -- 
      elapsed = realToFrac (diffUTCTime now zero)
  return (dt, elapsed) -- ( now - prev, now - zero aka start)

-- initialize reactimate
inits :: IO (S.Set (Sign (S.Set (Sign Nat))), DTime)
inits = return (S.singleton (Sign (S.singleton (Sign Zero))), 0)

-- compute satisfaction of mod and sen from signature morphism and witness
input :: (IORef Stopwatch) -> Bool -> IO (DTime, Maybe Input)
input ref _ = do
  (delta, elapsed) <- diffTimes ref
  print elapsed
  let sigMo = (Pred . Suc) 
  sat <- return $ ((arr (runDual (Dual $ arr mapSign)) >>> arr (fmap S.singleton)) >>> (arr mapSign >>> arr (fmap S.singleton)) $ sigMo)
  let witness = Sign (Sign Zero)
  let r = sat $ witness
  return (delta, (Just (r, elapsed)))         

output' :: Bool -> Output -> IO Bool
output' _ Nothing = return True
output' _ (Just a) = print a >> return False -- return s

-- signal function
process :: SF Input Output
process = arr fn
           where
             fn (n, elapsed)
                | elapsed <= 1 = Just n
                | otherwise = Nothing

main = do
  handle <- storeWatch
  reactimate inits (input handle) output' process