module Data.Geometry.Ipe.IpeView where

import Data.Geometry.Ipe.IpeTypes
import Data.Geometry.Ipe.IGC
import Data.List

import qualified Data.Map as M

data Layer a = Layer { layerDef ::  LayerDefinition
                     , layerContent :: IGC a
                     }
               deriving (Show,Eq)

data ViewInstance a = ViewInstance { viewDef :: ViewDefinition
                                   , layers  :: [Layer a]
                                   }
                    deriving (Show,Eq)




-- | Given a set of layers construct a view instance. The first layer is used as
-- active layer.
viewInstance :: [Layer a]  -> ViewInstance a
viewInstance lrs = ViewInstance vd lrs
                   where
                     a   = layerDef . head  $ lrs
                     lns = nub $ map layerDef lrs
                     vd  = ViewDefinition lns a


addLayer                        :: Layer a -> ViewInstance a -> ViewInstance a
addLayer l@(Layer name _) (ViewInstance (ViewDefinition lns a) ls) =
    ViewInstance (ViewDefinition lns' a) (l:ls)
        where
          lns' = nub (name:lns)

-- | Make a new layer, and add the elements in the given collection to this layer
layer                              :: String -> IGC a -> Layer a
layer name (IGC n pts pll sps mps) = Layer name gc
                  where
                    f  ::HasAttributes g => g -> g
                    f  = updateWith (M.alter (const $ Just name) "layer")
                    gc = IGC n (map f pts) (map f pll) (map f sps) (map f mps)