{-# LANGUAGE NamedFieldPuns #-}
module Cardano.Node.Socket.Emulator.Params where

import Cardano.Api.Shelley (ProtocolParameters)
import Cardano.Node.Emulator.Internal.Node.Params
import Cardano.Node.Socket.Emulator.Types
import Data.Aeson (eitherDecode)
import Data.ByteString.Lazy qualified as BSL
import Data.Default (def)

fromNodeServerConfig :: NodeServerConfig -> IO Params
fromNodeServerConfig :: NodeServerConfig -> IO Params
fromNodeServerConfig NodeServerConfig{SlotConfig
nscSlotConfig :: NodeServerConfig -> SlotConfig
nscSlotConfig :: SlotConfig
nscSlotConfig, NetworkId
nscNetworkId :: NodeServerConfig -> NetworkId
nscNetworkId :: NetworkId
nscNetworkId, Maybe FilePath
nscProtocolParametersJsonPath :: NodeServerConfig -> Maybe FilePath
nscProtocolParametersJsonPath :: Maybe FilePath
nscProtocolParametersJsonPath} = do
  ProtocolParameters
protocolParameters <- Maybe FilePath -> IO ProtocolParameters
readProtocolParameters Maybe FilePath
nscProtocolParametersJsonPath
  Params -> IO Params
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Params -> IO Params) -> Params -> IO Params
forall a b. (a -> b) -> a -> b
$ SlotConfig -> ProtocolParameters -> NetworkId -> Params
paramsWithProtocolsParameters SlotConfig
nscSlotConfig ProtocolParameters
protocolParameters NetworkId
nscNetworkId

readProtocolParameters :: Maybe FilePath -> IO ProtocolParameters
readProtocolParameters :: Maybe FilePath -> IO ProtocolParameters
readProtocolParameters = IO ProtocolParameters
-> (FilePath -> IO ProtocolParameters)
-> Maybe FilePath
-> IO ProtocolParameters
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProtocolParameters -> IO ProtocolParameters
forall (f :: * -> *) a. Applicative f => a -> f a
pure ProtocolParameters
forall a. Default a => a
def) FilePath -> IO ProtocolParameters
forall b. FromJSON b => FilePath -> IO b
readPP
  where
    readPP :: FilePath -> IO b
readPP FilePath
path = do
      ByteString
bs <- FilePath -> IO ByteString
BSL.readFile FilePath
path
      case ByteString -> Either FilePath b
forall a. FromJSON a => ByteString -> Either FilePath a
eitherDecode ByteString
bs of
        Left FilePath
err -> FilePath -> IO b
forall a. HasCallStack => FilePath -> a
error (FilePath -> IO b) -> FilePath -> IO b
forall a b. (a -> b) -> a -> b
$ FilePath
"Error reading protocol parameters JSON file: "
                         FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath -> FilePath
forall a. Show a => a -> FilePath
show FilePath
path FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
" (" FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
err FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
")"
        Right b
params -> b -> IO b
forall (f :: * -> *) a. Applicative f => a -> f a
pure b
params