{-
The MIT License (MIT)

Copyright (c) 2015 Wasif Hasan Baig <pr.wasif@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}

{- |
   Module      : Text.Table.Helper
   Copyright   : Copyright (C) 2015 Wasif Hasan Baig
   License     : MIT

   Maintainer  : Venkateswara Rao Mandela <venkat.mandela@gmail.com>
   Stability   : alpha

This helper module exports functions extract values from Pandoc AST and 
build Pandoc Document from CSV.
-}

module Text.Table.Helper (
      addInlineLabel
    , getTableType
    , toTableType
    , getAligns
    , isHeaderPresent
    , isHeaderPresent1
    , removeConfigString
    , toBlocks
    , getAtr
    , toAlign
    , tableFromImageInline
    , tableFromCodeBlock
    , getString
    , applyToTuple
) where

import Text.CSV (CSV)
import Data.List (isInfixOf)
import Text.Pandoc (readMarkdown, def, ReaderOptions, readerExtensions)
#if MIN_VERSION_pandoc(2, 0, 0)
-- Extensions was split from Options in 2.0.0
import Text.Pandoc.Extensions
#else
import Text.Pandoc (pandocExtensions)
#endif
import qualified Text.Pandoc.JSON as J
-- Local imports
import Text.Table.Definition
import Text.Table.Builder
-- imports for compatibility with Pandoc 2.0+
#if MIN_VERSION_pandoc(2,0,0)
import Text.Pandoc (runPure)
import Data.Text (pack, unpack)
#endif

#if MIN_VERSION_pandoc(2,9,0)
getString :: Text -> String
getString = Text -> String
unpack
#else
getString = id
#endif

applyToTuple :: (a -> b) -> (a, a) -> (b, b)
applyToTuple :: (a -> b) -> (a, a) -> (b, b)
applyToTuple a -> b
f (a
x, a
y) = ((a -> b
f a
x), (a -> b
f a
y))

-- Helper functions to manipulate the Pandoc Document and parse the 
-- Configuration String.

-- | Add Inline from Image into Table as the caption
addInlineLabel :: [J.Inline] -> J.Pandoc -> J.Pandoc
#if MIN_VERSION_pandoc_types(1,21,0)
addInlineLabel :: [Inline] -> Pandoc -> Pandoc
addInlineLabel [Inline]
i (J.Pandoc Meta
m [(J.Table Attr
attr Caption
_ [ColSpec]
colSpec TableHead
tableHead [TableBody]
tableBody TableFoot
tableFoot)]) = Meta -> [Block] -> Pandoc
J.Pandoc Meta
m [(Attr
-> Caption
-> [ColSpec]
-> TableHead
-> [TableBody]
-> TableFoot
-> Block
J.Table Attr
attr Caption
inlineCaption [ColSpec]
colSpec TableHead
tableHead [TableBody]
tableBody TableFoot
tableFoot)]
                                                                                          where inlineCaption :: Caption
inlineCaption = Maybe [Inline] -> [Block] -> Caption
J.Caption (Maybe [Inline]
forall a. Maybe a
Nothing) [[Inline] -> Block
J.Plain [Inline]
i] -- We dont support ShortCaption
#else
addInlineLabel i (J.Pandoc m [(J.Table _ as ds ts tss)]) = J.Pandoc m [(J.Table i as ds ts tss)]
#endif
addInlineLabel [Inline]
_ Pandoc
x = Pandoc
x

-- | Extracts Blocks from Pandoc Document
toBlocks :: J.Pandoc -> [J.Block]
toBlocks :: Pandoc -> [Block]
toBlocks (J.Pandoc Meta
_ [Block]
bs) = [Block]
bs

toTableType1 :: String -> TableType
toTableType1 :: String -> TableType
toTableType1 (Char
x:String
ys) = case Char
x of
                       Char
's' -> TableType
Simple
                       Char
'm' -> TableType
Multiline
                       Char
'p' -> TableType
Pipe
                       Char
_   -> TableType
Grid
toTableType1 []     = TableType
Grid

toTableType :: String -> TableType
toTableType :: String -> TableType
toTableType String
s = case String
s of
                  String
"simple"    -> TableType
Simple
                  String
"multiline" -> TableType
Multiline
                  String
"pipe"      -> TableType
Pipe
                  String
_           -> TableType
Grid

getTableType :: [J.Inline] -> TableType
getTableType :: [Inline] -> TableType
getTableType ((J.Str Text
s):[]) = String -> TableType
toTableType1 (Text -> String
getString Text
s)
getTableType (Inline
_:[Inline]
is)         = [Inline] -> TableType
getTableType [Inline]
is
getTableType []             = TableType
Grid

-- | Whether to treat first line of CSV as a header or not.
isHeaderPresent :: [J.Inline] -> Bool
isHeaderPresent :: [Inline] -> Bool
isHeaderPresent ((J.Str Text
s):[]) = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ String
"n" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` (Text -> String
getString Text
s)
isHeaderPresent (Inline
_:[Inline]
is)         = [Inline] -> Bool
isHeaderPresent [Inline]
is
isHeaderPresent []             = Bool
True

isHeaderPresent1 :: String -> Bool
isHeaderPresent1 :: String -> Bool
isHeaderPresent1 (Char
'n':Char
'o':[]) = Bool
False
isHeaderPresent1 String
_            = Bool
True

toAlign :: String -> [Align]
toAlign :: String -> [Align]
toAlign (Char
x:String
ys) = case Char
x of
                   Char
'l' -> Align
LeftAlign    Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'L' -> Align
LeftAlign    Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'r' -> Align
RightAlign   Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'R' -> Align
RightAlign   Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'c' -> Align
CenterAlign  Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'C' -> Align
CenterAlign  Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'd' -> Align
DefaultAlign Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
'D' -> Align
DefaultAlign Align -> [Align] -> [Align]
forall a. a -> [a] -> [a]
: String -> [Align]
toAlign String
ys
                   Char
_   -> []          [Align] -> [Align] -> [Align]
forall a. [a] -> [a] -> [a]
++ String -> [Align]
toAlign String
ys
toAlign []     = []

-- | Parse Config String for alignment information
getAligns :: [J.Inline] -> [Align]
getAligns :: [Inline] -> [Align]
getAligns ((J.Str Text
s):[]) = String -> [Align]
toAlign (Text -> String
getString Text
s)
getAligns (Inline
_:[Inline]
is)         = [Inline] -> [Align]
getAligns [Inline]
is
getAligns []             = []

-- | Remove Str Inline from caption
removeConfigString :: [J.Inline] -> [J.Inline]
removeConfigString :: [Inline] -> [Inline]
removeConfigString (Inline
_:[]) = []
removeConfigString (Inline
x:[Inline]
ys) = Inline
x Inline -> [Inline] -> [Inline]
forall a. a -> [a] -> [a]
: [Inline] -> [Inline]
removeConfigString [Inline]
ys
removeConfigString []     = []

-- | Get value of attribute
getAtr :: AtrName -> Atrs -> AtrValue
getAtr :: String -> Atrs -> String
getAtr String
a ((String
at,String
v):Atrs
_) | String
a String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
at = String
v
getAtr String
a ((String, String)
_:Atrs
xs)               = String -> Atrs -> String
getAtr String
a Atrs
xs
getAtr String
a []                   = String
""

ropt :: ReaderOptions
ropt :: ReaderOptions
ropt = ReaderOptions
forall a. Default a => a
def
    {
      -- In the below Pandoc commit,
      --
      -- https://github.com/jgm/pandoc/commit/a58369a7e65075800
      --
      -- the default reader options were changed from pandocExtensions to
      -- empty. This resulted in the markdown to Pandoc AST conversion
      -- failing
      --
      -- To fix this issue, we enable the required reader options in
      -- pandoc-csv2table.
      readerExtensions :: Extensions
readerExtensions = Extensions
pandocExtensions
    }

-- The conversion happens in three stages
-- 1. Convert the CSV to an internal table representation
-- 2. Convert internal table representation to markdown
-- 3. Convert markdown into Pandoc AST.
--
-- Converting from internal table representation to Pandoc AST
-- via markdown decouples internal table representation from
-- Pandoc AST changes.
--
-- TODO: What is the downside of going directly from CSV to Pandoc
-- table representation?

-- | Make Pandoc Table from Image Inline 
tableFromImageInline :: [J.Inline] -> CSV -> J.Pandoc
tableFromImageInline :: [Inline] -> CSV -> Pandoc
tableFromImageInline [Inline]
l = [Inline] -> Pandoc -> Pandoc
addInlineLabel ([Inline] -> [Inline]
removeConfigString [Inline]
l) (Pandoc -> Pandoc) -> (CSV -> Pandoc) -> CSV -> Pandoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                         ReaderOptions -> String -> Pandoc
readMarkdown' ReaderOptions
ropt (String -> Pandoc) -> (CSV -> String) -> CSV -> Pandoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                         TableType -> CaptionPos -> Table -> String
toMarkdown ([Inline] -> TableType
getTableType [Inline]
l) CaptionPos
AfterTable (Table -> String) -> (CSV -> Table) -> CSV -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                         String -> [Align] -> Bool -> CSV -> Table
mkTable String
"" ([Inline] -> [Align]
getAligns [Inline]
l) ([Inline] -> Bool
isHeaderPresent [Inline]
l)

-- | Make Pandoc Table from Code Block 
tableFromCodeBlock :: Atrs -> CSV -> J.Pandoc
tableFromCodeBlock :: Atrs -> CSV -> Pandoc
tableFromCodeBlock Atrs
as = ReaderOptions -> String -> Pandoc
readMarkdown' ReaderOptions
ropt (String -> Pandoc) -> (CSV -> String) -> CSV -> Pandoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                        TableType -> CaptionPos -> Table -> String
toMarkdown (String -> TableType
toTableType (String -> TableType) -> String -> TableType
forall a b. (a -> b) -> a -> b
$ String -> Atrs -> String
getAtr String
"type" Atrs
as) CaptionPos
AfterTable (Table -> String) -> (CSV -> Table) -> CSV -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.
                        String -> [Align] -> Bool -> CSV -> Table
mkTable (String -> Atrs -> String
getAtr String
"caption" Atrs
as)
                                (String -> [Align]
toAlign (String -> [Align]) -> String -> [Align]
forall a b. (a -> b) -> a -> b
$ String -> Atrs -> String
getAtr String
"aligns" Atrs
as)
                                (String -> Bool
isHeaderPresent1 (String -> Bool) -> String -> Bool
forall a b. (a -> b) -> a -> b
$ String -> Atrs -> String
getAtr String
"header" Atrs
as)
#if MIN_VERSION_pandoc(2,0,0)
-- Pandoc now operates on Data.Text instead of String. So we pack the string
-- before calling readMarkdown.
-- The function signature of readMarkdown has changed. It now returns a PandocMonad
-- instead of Pandoc. We run readMarkdown in runPure to indicate we are not doing IO
-- and handle the output in the same manner as in 1.14 migration.
readMarkdown' :: ReaderOptions -> String -> J.Pandoc
readMarkdown' :: ReaderOptions -> String -> Pandoc
readMarkdown' ReaderOptions
o String
s = case Either PandocError Pandoc
parsed of
  (Left PandocError
_) -> Meta -> [Block] -> Pandoc
J.Pandoc Meta
J.nullMeta []
  (Right Pandoc
p) -> Pandoc
p
  where parsed :: Either PandocError Pandoc
parsed = PandocPure Pandoc -> Either PandocError Pandoc
forall a. PandocPure a -> Either PandocError a
runPure (ReaderOptions -> Text -> PandocPure Pandoc
forall (m :: * -> *).
PandocMonad m =>
ReaderOptions -> Text -> m Pandoc
readMarkdown ReaderOptions
o (Text -> PandocPure Pandoc) -> Text -> PandocPure Pandoc
forall a b. (a -> b) -> a -> b
$ String -> Text
pack String
s)

#elif MIN_VERSION_pandoc(1,14,0)
readMarkdown' :: ReaderOptions -> String -> J.Pandoc
readMarkdown' o s = case read of
                      (Left _)  -> J.Pandoc J.nullMeta []
                      (Right p) -> p
                  where read = readMarkdown o s
#else
readMarkdown' :: ReaderOptions -> String -> J.Pandoc
readMarkdown' = readMarkdown
#endif