{-|
Rendering a journal's items back to journal format, reproducing the
original journal file(s). Used by print --export.
-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Hledger.Write.Journal (
  ItemRenderer(..),
  journalItemRenderer,
  journalItemsAsText,
) where

import Data.List (mapAccumL)
import Data.Map qualified as M
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as TB
import Text.Megaparsec.Pos (SourcePos(..), unPos)

import Hledger.Data.Types

-- | How to render each kind of journal item in some output format.
data ItemRenderer = ItemRenderer
  { ItemRenderer -> Transaction -> Text
irTransaction  :: Transaction -> Text  -- ^ render a transaction, without a trailing blank line
  , ItemRenderer -> Text -> Maybe Text
irDirective    :: Text -> Maybe Text   -- ^ render a directive given as source text, or drop it (Nothing)
  , ItemRenderer -> Text -> Text
irComment      :: Text -> Text         -- ^ render a top-level comment line
  , ItemRenderer -> Text -> Text
irCommentBlock :: Text -> Text         -- ^ render a comment ... end comment block
  }

-- | An item renderer for hledger's journal format, reproducing directives and comments as written,
-- and rendering transactions with the given showTransaction-like function
-- (whose trailing blank line is removed).
journalItemRenderer :: (Transaction -> Text) -> ItemRenderer
journalItemRenderer :: (Transaction -> Text) -> ItemRenderer
journalItemRenderer Transaction -> Text
showtxn = ItemRenderer
  { irTransaction :: Transaction -> Text
irTransaction  = \Transaction
t -> let s :: Text
s = Transaction -> Text
showtxn Transaction
t in Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
s (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripSuffix Text
"\n" Text
s
  , irDirective :: Text -> Maybe Text
irDirective    = Text -> Maybe Text
forall a. a -> Maybe a
Just
  , irComment :: Text -> Text
irComment      = Text -> Text
forall a. a -> a
id
  , irCommentBlock :: Text -> Text
irCommentBlock = Text -> Text
forall a. a -> a
id
  }

-- | Render journal items as journal text, reproducing the journal file(s) they were parsed from,
-- with transactions rendered from the given (possibly filtered and processed) transactions.
--
-- Directive, comment line and comment block items are rendered as the item renderer specifies
-- (verbatim, for hledger's journal format).
-- Non-exported directives are dropped. Include lines are dropped too, and the included file's
-- items follow inline, beginning a new block (so eg there is a blank line between the entries
-- of adjacent included files).
-- Each transaction placeholder is replaced by the rendering of the next given transaction
-- with that source position, or by nothing if there is none (eg it was filtered out).
-- Any transactions not matching a placeholder (eg from non-journal files) are added at the end,
-- in source position order.
--
-- Blank lines are normalised: each transaction, and each group of adjacent directive/comment
-- items (as delimited by blank lines in the source), is a block, and blocks are separated
-- by exactly one blank line. A final transaction is also followed by a blank line, as in
-- ordinary print output.
journalItemsAsText :: ItemRenderer -> [JournalItem] -> [Transaction] -> TL.Text
journalItemsAsText :: ItemRenderer -> [JournalItem] -> [Transaction] -> Text
journalItemsAsText ItemRenderer{Text -> Maybe Text
Text -> Text
Transaction -> Text
irTransaction :: ItemRenderer -> Transaction -> Text
irDirective :: ItemRenderer -> Text -> Maybe Text
irComment :: ItemRenderer -> Text -> Text
irCommentBlock :: ItemRenderer -> Text -> Text
irTransaction :: Transaction -> Text
irDirective :: Text -> Maybe Text
irComment :: Text -> Text
irCommentBlock :: Text -> Text
..} [JournalItem]
items [Transaction]
txns =
  Builder -> Text
TB.toLazyText (Builder -> Text) -> Builder -> Text
forall a b. (a -> b) -> a -> b
$ [Block] -> Builder
renderBlocks ([Block] -> Builder) -> [Block] -> Builder
forall a b. (a -> b) -> a -> b
$ [Block] -> [Block]
mergeGroups ([Block] -> [Block]) -> [Block] -> [Block]
forall a b. (a -> b) -> a -> b
$ [[Block]] -> [Block]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[Block]]
blockss [Block] -> [Block] -> [Block]
forall a. Semigroup a => a -> a -> a
<> (Transaction -> Block) -> [Transaction] -> [Block]
forall a b. (a -> b) -> [a] -> [b]
map Transaction -> Block
txnBlock ([[Transaction]] -> [Transaction]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[Transaction]] -> [Transaction])
-> [[Transaction]] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ Map (Int, Int, String) [Transaction] -> [[Transaction]]
forall k a. Map k a -> [a]
M.elems Map (Int, Int, String) [Transaction]
remaining)
  where
    -- transactions queued by source position, in the given order
    txnsbypos :: Map (Int, Int, String) [Transaction]
txnsbypos = ([Transaction] -> [Transaction])
-> Map (Int, Int, String) [Transaction]
-> Map (Int, Int, String) [Transaction]
forall a b k. (a -> b) -> Map k a -> Map k b
M.map [Transaction] -> [Transaction]
forall a. [a] -> [a]
reverse (Map (Int, Int, String) [Transaction]
 -> Map (Int, Int, String) [Transaction])
-> Map (Int, Int, String) [Transaction]
-> Map (Int, Int, String) [Transaction]
forall a b. (a -> b) -> a -> b
$ ([Transaction] -> [Transaction] -> [Transaction])
-> [((Int, Int, String), [Transaction])]
-> Map (Int, Int, String) [Transaction]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith [Transaction] -> [Transaction] -> [Transaction]
forall a. [a] -> [a] -> [a]
(++) [(SourcePos -> (Int, Int, String)
posKey (SourcePos -> (Int, Int, String))
-> SourcePos -> (Int, Int, String)
forall a b. (a -> b) -> a -> b
$ (SourcePos, SourcePos) -> SourcePos
forall a b. (a, b) -> a
fst ((SourcePos, SourcePos) -> SourcePos)
-> (SourcePos, SourcePos) -> SourcePos
forall a b. (a -> b) -> a -> b
$ Transaction -> (SourcePos, SourcePos)
tsourcepos Transaction
t, [Transaction
t]) | Transaction
t <- [Transaction]
txns]
    -- A map key comparing line and column before the file path, since comparing
    -- SourcePos directly compares the (usually identical) file paths first, which is slow.
    posKey :: SourcePos -> (Int, Int, String)
posKey (SourcePos String
f Pos
l Pos
c) = (Pos -> Int
unPos Pos
l, Pos -> Int
unPos Pos
c, String
f)
    txnBlock :: Transaction -> Block
txnBlock = Builder -> Block
Txn (Builder -> Block)
-> (Transaction -> Builder) -> Transaction -> Block
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Builder
TB.fromText (Text -> Builder)
-> (Transaction -> Text) -> Transaction -> Builder
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Text
irTransaction
    linesBlock :: Text -> Block
linesBlock = Builder -> Block
Lines (Builder -> Block) -> (Text -> Builder) -> Text -> Block
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Builder
TB.fromText

    -- Convert each item to a block (or none), consuming the queued transactions.
    -- (Keep this pattern binding flat, so the final state doesn't retain the blocks list.)
    (Map (Int, Int, String) [Transaction]
remaining, [[Block]]
blockss) = (Map (Int, Int, String) [Transaction]
 -> JournalItem -> (Map (Int, Int, String) [Transaction], [Block]))
-> Map (Int, Int, String) [Transaction]
-> [JournalItem]
-> (Map (Int, Int, String) [Transaction], [[Block]])
forall (t :: * -> *) s a b.
Traversable t =>
(s -> a -> (s, b)) -> s -> t a -> (s, t b)
mapAccumL Map (Int, Int, String) [Transaction]
-> JournalItem -> (Map (Int, Int, String) [Transaction], [Block])
toBlock Map (Int, Int, String) [Transaction]
txnsbypos [JournalItem]
items
    toBlock :: Map (Int, Int, String) [Transaction]
-> JournalItem -> (Map (Int, Int, String) [Transaction], [Block])
toBlock Map (Int, Int, String) [Transaction]
m JournalItem
item = case JournalItem
item of
      JITransaction SourcePos
pos -> case (Int, Int, String)
-> Map (Int, Int, String) [Transaction] -> Maybe [Transaction]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Int, Int, String)
k Map (Int, Int, String) [Transaction]
m of
          Just (Transaction
t:[Transaction]
ts) -> ((Int, Int, String)
-> [Transaction]
-> Map (Int, Int, String) [Transaction]
-> Map (Int, Int, String) [Transaction]
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert (Int, Int, String)
k [Transaction]
ts Map (Int, Int, String) [Transaction]
m, [Transaction -> Block
txnBlock Transaction
t])
          Maybe [Transaction]
_           -> (Map (Int, Int, String) [Transaction]
m, [Block
Break])
        where k :: (Int, Int, String)
k = SourcePos -> (Int, Int, String)
posKey SourcePos
pos
      JournalItem
JIBlank                  -> (Map (Int, Int, String) [Transaction]
m, [Block
Break])
      JIComment Text
t              -> (Map (Int, Int, String) [Transaction]
m, [Text -> Block
linesBlock (Text -> Block) -> Text -> Block
forall a b. (a -> b) -> a -> b
$ Text -> Text
irComment Text
t])
      JICommentBlock Text
t         -> (Map (Int, Int, String) [Transaction]
m, [Text -> Block
linesBlock (Text -> Block) -> Text -> Block
forall a b. (a -> b) -> a -> b
$ Text -> Text
irCommentBlock Text
t])
      JIDirective Text
t            -> (Map (Int, Int, String) [Transaction]
m, (Text -> Block) -> [Text] -> [Block]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Block
linesBlock ([Text] -> [Block]) -> [Text] -> [Block]
forall a b. (a -> b) -> a -> b
$ [Text] -> (Text -> [Text]) -> Maybe Text -> [Text]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Text -> [Text]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Text -> [Text]) -> Maybe Text -> [Text]
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
irDirective Text
t)
      JINonExportedDirective Text
_ -> (Map (Int, Int, String) [Transaction]
m, [])
      JIInclude Text
_              -> (Map (Int, Int, String) [Transaction]
m, [Block
Break])  -- the included file's items begin a new block

-- | An output block: a group of directive/comment lines, a transaction, or a break between groups.
data Block = Lines TB.Builder | Txn TB.Builder | Break

-- | Merge adjacent line groups, and drop the breaks.
mergeGroups :: [Block] -> [Block]
mergeGroups :: [Block] -> [Block]
mergeGroups (Lines Builder
a : Lines Builder
b : [Block]
bs) = [Block] -> [Block]
mergeGroups (Builder -> Block
Lines (Builder
a Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
b) Block -> [Block] -> [Block]
forall a. a -> [a] -> [a]
: [Block]
bs)
mergeGroups (Block
Break : [Block]
bs)             = [Block] -> [Block]
mergeGroups [Block]
bs
mergeGroups (Block
b : [Block]
bs)                 = Block
b Block -> [Block] -> [Block]
forall a. a -> [a] -> [a]
: [Block] -> [Block]
mergeGroups [Block]
bs
mergeGroups []                       = []

-- | Render blocks separated by single blank lines. A final transaction is also
-- followed by a blank line, like ordinary print output; a final line group is not.
renderBlocks :: [Block] -> TB.Builder
renderBlocks :: [Block] -> Builder
renderBlocks []        = Builder
forall a. Monoid a => a
mempty
renderBlocks [Lines Builder
b] = Builder
b
renderBlocks (Block
b : [Block]
bs)  = Block -> Builder
blockBuilder Block
b Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Char -> Builder
TB.singleton Char
'\n' Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> [Block] -> Builder
renderBlocks [Block]
bs
  where
    blockBuilder :: Block -> Builder
blockBuilder (Lines Builder
b') = Builder
b'
    blockBuilder (Txn Builder
b')   = Builder
b'
    blockBuilder Block
Break      = Builder
forall a. Monoid a => a
mempty