-- SPDX-FileCopyrightText: 2020 Tocqueville Group
--
-- SPDX-License-Identifier: LicenseRef-MIT-TQ

-- | Module containing pretty-printing of Indigo contracts

module Indigo.Print
  ( printIndigoContract
  , renderIndigoDoc

  , printAsMichelson
  , saveAsMichelson
  , printDocumentation
  , saveDocumentation
  ) where

import Data.Text.Lazy.IO.Utf8 (writeFile)

import Indigo.Compilation
import Indigo.Internal.Object
import Indigo.Lorentz
import Indigo.Prelude

-- | Pretty-print an Indigo contract into Michelson code.
printIndigoContract
  :: forall param st .
     ( IsObject st
     , NiceParameterFull param
     , NiceStorage st
     )
  => Bool -- ^ Force result to be single line
  -> IndigoContract param st
  -> LText
printIndigoContract forceSingleLine ctr = printLorentzContract forceSingleLine $
  defaultContract $
  compileIndigoContract @param @st ctr

-- | Generate an Indigo contract documentation.
renderIndigoDoc
  :: forall param st .
     ( IsObject st
     , NiceParameterFull param
     )
  => IndigoContract param st
  -> LText
renderIndigoDoc ctr =
  renderLorentzDocWithGitRev DGitRevisionUnknown $ compileIndigoContract @param @st ctr

-- | Prints the pretty-printed Michelson code of an Indigo contract to
-- the standard output.
--
-- This is intended to be easy to use for newcomers.
printAsMichelson
  :: forall param st m . ( IsObject st
     , NiceParameterFull param, NiceStorage st
     , MonadIO m
     )
  => IndigoContract param st
  -> m ()
printAsMichelson cntr = putStrLn (printIndigoContract @param @st False cntr)

-- | Saves the pretty-printed Michelson code of an Indigo contract to
-- the given file.
--
-- This is intended to be easy to use for newcomers.
saveAsMichelson
  :: forall param st m . ( IsObject st
     , NiceParameterFull param, NiceStorage st
     , MonadIO m, MonadMask m
     )
  => IndigoContract param st
  -> FilePath
  -> m ()
saveAsMichelson cntr filePath =
  writeFile filePath (printIndigoContract @param @st False cntr)

-- | Print the generated documentation to the standard output.
printDocumentation
  :: forall param st m . ( IsObject st
     , NiceParameterFull param
     , MonadIO m
     )
  => IndigoContract param st
  -> m ()
printDocumentation ctr =
  putStrLn $ renderIndigoDoc @param @st ctr

-- | Save the generated documentation to the given file.
saveDocumentation
  :: forall param st m . ( IsObject st
     , NiceParameterFull param
     , MonadIO m, MonadMask m
     )
  => IndigoContract param st
  -> FilePath
  -> m ()
saveDocumentation ctr filePath = do
  writeFile filePath (renderIndigoDoc @param @st ctr)
