1{-# LANGUAGE OverloadedStrings, RecordWildCards, CPP #-}
2
3module Case where
4
5#if __GLASGOW_HASKELL__ < 709
6import Control.Applicative ((<$>))
7#endif
8import Data.ByteString (ByteString)
9import qualified Data.ByteString.Base16 as B16
10
11import JSON
12import Network.HTTP2
13
14data CaseSource = CaseSource {
15    cs_description :: String
16  , cs_encodeinfo :: EncodeInfo
17  , cs_payload :: FramePayload
18  } deriving (Show,Read)
19
20data CaseWire = CaseWire {
21    wire_description :: String
22  , wire_hex :: ByteString
23  , wire_padding :: Maybe Pad
24  , wire_error :: Maybe [ErrorCodeId]
25  } deriving (Show,Read)
26
27sourceToWire :: CaseSource -> CaseWire
28sourceToWire CaseSource{..} = CaseWire {
29    wire_description = cs_description
30  , wire_hex = wire
31  , wire_padding = Pad <$> encodePadding cs_encodeinfo
32  , wire_error = Nothing
33  }
34  where
35    frame = encodeFrame cs_encodeinfo cs_payload
36    wire = B16.encode frame
37
38wireToCase :: CaseWire -> Case
39wireToCase CaseWire { wire_error = Nothing, ..} = Case {
40    description = wire_description
41  , wire = wire_hex
42  , frame = Just $ FramePad frm wire_padding
43  , err = Nothing
44  }
45  where
46    -- fromJust is unsafe
47    frm = case decodeFrame defaultSettings $ B16.decodeLenient wire_hex of
48        Left  e -> error $ show e
49        Right r -> r
50wireToCase CaseWire { wire_error = Just e, ..} = Case {
51    description = wire_description
52  , wire = wire_hex
53  , frame = Nothing
54  , err = Just $ fromErrorCodeId <$> e
55  }
56