{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Codec.Xlsx.Types.Internal.DvPair where

import qualified Data.Map as M
import GHC.Generics (Generic)
import Text.XML (Element(..))

import Codec.Xlsx.Parser.Internal
import Codec.Xlsx.Types.Common
import Codec.Xlsx.Types.DataValidation
import Codec.Xlsx.Writer.Internal

-- | Internal helper type for parsing data validation records
--
-- See 18.3.1.32 "dataValidation (Data Validation)" (p. 1614/1624)
newtype DvPair = DvPair
    { DvPair -> (SqRef, DataValidation)
unDvPair :: (SqRef, DataValidation)
    } deriving (DvPair -> DvPair -> Bool
(DvPair -> DvPair -> Bool)
-> (DvPair -> DvPair -> Bool) -> Eq DvPair
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DvPair -> DvPair -> Bool
== :: DvPair -> DvPair -> Bool
$c/= :: DvPair -> DvPair -> Bool
/= :: DvPair -> DvPair -> Bool
Eq, Int -> DvPair -> ShowS
[DvPair] -> ShowS
DvPair -> String
(Int -> DvPair -> ShowS)
-> (DvPair -> String) -> ([DvPair] -> ShowS) -> Show DvPair
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DvPair -> ShowS
showsPrec :: Int -> DvPair -> ShowS
$cshow :: DvPair -> String
show :: DvPair -> String
$cshowList :: [DvPair] -> ShowS
showList :: [DvPair] -> ShowS
Show, (forall x. DvPair -> Rep DvPair x)
-> (forall x. Rep DvPair x -> DvPair) -> Generic DvPair
forall x. Rep DvPair x -> DvPair
forall x. DvPair -> Rep DvPair x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. DvPair -> Rep DvPair x
from :: forall x. DvPair -> Rep DvPair x
$cto :: forall x. Rep DvPair x -> DvPair
to :: forall x. Rep DvPair x -> DvPair
Generic)

instance FromCursor DvPair where
    fromCursor :: Cursor -> [DvPair]
fromCursor Cursor
cur = do
        sqref <- Name -> Cursor -> [SqRef]
forall a. FromAttrVal a => Name -> Cursor -> [a]
fromAttribute Name
"sqref" Cursor
cur
        dv    <- fromCursor cur
        return $ DvPair (sqref, dv)

instance FromXenoNode DvPair where
  fromXenoNode :: Node -> Either Text DvPair
fromXenoNode Node
root = do
    sqref <- Node -> AttrParser SqRef -> Either Text SqRef
forall a. Node -> AttrParser a -> Either Text a
parseAttributes Node
root (AttrParser SqRef -> Either Text SqRef)
-> AttrParser SqRef -> Either Text SqRef
forall a b. (a -> b) -> a -> b
$ ByteString -> AttrParser SqRef
forall a. FromAttrBs a => ByteString -> AttrParser a
fromAttr ByteString
"sqref"
    dv <- fromXenoNode root
    return $ DvPair (sqref, dv)

instance ToElement DvPair where
    toElement :: Name -> DvPair -> Element
toElement Name
nm (DvPair (SqRef
sqRef,DataValidation
dv)) = Element
e
        {elementAttributes = M.insert "sqref" (toAttrVal sqRef) $ elementAttributes e}
      where
        e :: Element
e = Name -> DataValidation -> Element
forall a. ToElement a => Name -> a -> Element
toElement Name
nm DataValidation
dv