module Quantum.Random.Codec (
QRResponse (..),
QRSettings (..),
defaults,
parseResponse,
parseSettings,
updateTarSize,
updateMinSize,
updateDefaultStyle
) where
import Quantum.Random.Exceptions
import Quantum.Random.Display
import GHC.Generics (Generic)
import Data.Aeson (FromJSON,ToJSON,eitherDecode)
import Data.Text (Text)
import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Lazy.Char8 (pack,unpack)
import Text.Regex.Posix ((=~))
import Data.Bifunctor (first)
data QRResponse = QRResponse { qtype :: !Text
, qlength :: !Int
, qdata :: ![Int]
, success :: !Bool } deriving (Show, Generic)
data QRSettings = QRSettings { minStoreSize :: Int
, targetStoreSize :: Int
, defaultDisplayStyle :: DisplayStyle } deriving (Show, Generic)
instance FromJSON QRResponse
instance ToJSON QRResponse
instance FromJSON QRSettings
instance ToJSON QRSettings
defaults :: QRSettings
defaults = QRSettings 400 800 ColorHex
updateMinSize :: Int -> QRSettings -> QRSettings
updateMinSize n qs = qs { minStoreSize = n }
updateTarSize :: Int -> QRSettings -> QRSettings
updateTarSize n qs = qs { targetStoreSize = n }
updateDefaultStyle :: DisplayStyle -> QRSettings -> QRSettings
updateDefaultStyle sty qs = qs { defaultDisplayStyle = sty }
process :: ByteString -> ByteString
process = pack . repData . repType . repLength . unpack
repData :: String -> String
repData = replaceWord "data" "qdata"
repType :: String -> String
repType = replaceWord "type" "qtype"
repLength :: String -> String
repLength = replaceWord "length" "qlength"
replaceWord :: String -> String -> String -> String
replaceWord x y s = let (a,_,c) = s =~ x :: (String, String, String)
in a ++ y ++ c
parseResponse :: ByteString -> Either QRException QRResponse
parseResponse = first ParseResponseError . eitherDecode . process
parseSettings :: ByteString -> Either QRException QRSettings
parseSettings = first ParseSettingsError . eitherDecode