{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}

module Language.Haskell.Brittany.Internal.Transformations.T5_Indent where

import qualified Data.Generics.Uniplate.Direct as Uniplate
import qualified GHC.OldList as List
import Language.Haskell.Brittany.Internal.Prelude
import Language.Haskell.Brittany.Internal.Components.BriDoc



-- prepare layouting by translating BDPar's, replacing them with Indents and
-- floating those in. This gives a more clear picture of what exactly is
-- affected by what amount of indentation.
transformSimplifyIndent :: BriDoc -> BriDoc
transformSimplifyIndent = Uniplate.rewrite $ \case
  -- BDPar ind (BDLines lines) indented ->
  --   Just $ BDEnsureIndent ind $ BDLines $ lines ++ [indented]
  BDPar ind (BDLines (line1:lineR)) indented ->
    Just
      $  BDLines
      $  [line1]
      ++ fmap (BDEnsureIndent ind) lineR
      ++ [BDEnsureIndent ind indented]
  BDPar ind (BDCols sig cols) indented ->
    Just $ BDCols sig (List.init cols ++ [BDPar ind (List.last cols) indented])
  BDPar BrIndentNone _ _ -> Nothing
  BDPar ind x indented ->
    Just $ BDPar BrIndentNone (BDAddBaseY ind x) (BDEnsureIndent ind indented)
  -- BDPar ind x indented ->
  --   Just $ BDLines
  --     [ BDAddBaseY ind x
  --     , BDEnsureIndent ind indented
  --     ]
  BDLines lines
    | any
      (\case
        BDLines{} -> True
        BDEmpty{} -> True
        _ -> False
      )
      lines
    -> Just $ BDLines $ filter isNotEmpty $ lines >>= \case
      BDLines l -> l
      x -> [x]
  BDLines [l] -> Just l
  BDAddBaseY i (BDFlushCommentsPrior c x) ->
    Just $ BDFlushCommentsPrior c (BDAddBaseY i x)
  BDAddBaseY i (BDFlushCommentsPost c sm x) ->
    Just $ BDFlushCommentsPost c sm (BDAddBaseY i x)
  BDAddBaseY i (BDQueueComments comms x) ->
    Just $ BDQueueComments comms (BDAddBaseY i x)
  BDAddBaseY i (BDSeq l) ->
    Just $ BDSeq $ List.init l ++ [BDAddBaseY i $ List.last l]
  BDAddBaseY i (BDCols sig l) ->
    Just $ BDCols sig $ List.init l ++ [BDAddBaseY i $ List.last l]
  BDAddBaseY _ lit@BDLit{} -> Just lit
  -- BDEnsureIndent (BrIndentSpecial a) (BDEnsureIndent (BrIndentSpecial b) x) ->
  --   Just $ BDEnsureIndent (BrIndentSpecial (a + b)) x
  -- BDEnsureIndent ind (BDCols op (c1:cR)) ->
  --   Just $ BDCols op (BDEnsureIndent ind c1 : cR)

  _ -> Nothing
