{-# LANGUAGE RankNTypes #-}
module Dodge.Graph
    ( pairsToSCC
    , incidenceToFunction
    , pairsToIncidence
    , graphToEdges
    ) where
-- this deserves tests
import Data.List.Extra

--import Data.Bifunctor (first)
import Data.Graph
import Data.Maybe
import qualified Data.Graph.Inductive.Graph as F
import qualified Data.Graph.Inductive.PatriciaTree as F
import Data.Bifunctor

pairsToIncidence :: Ord a => [(a,a)] -> [(a,[a])]
pairsToIncidence 
    = map (first head . unzip)
    . groupOn fst
    . sort

incidenceToFunction :: Eq a => [(a,[a])] -> a -> [a]
incidenceToFunction xs a = fromMaybe [] $ lookup a xs

mkNode :: (a,[a]) -> (a,a,[a])
mkNode (x,xs) = (x,x,xs)

pairsToSCC :: Ord a => [(a,a)] -> [SCC a]
pairsToSCC = stronglyConnComp . map mkNode . pairsToIncidence

graphToEdges :: forall a b . F.Gr a b -> [(a,a)]
graphToEdges g = map (bimap f f) $ F.edges g
  where
    f n = fromJust . lookup n $ F.labNodes g
