#!/usr/bin/env python3
# Copyright (C) 2007-20 Dr. Ralf Schlatterbeck Open Source Consulting.
# Reichergasse 131, A-3411 Weidling.
# Web: http://www.runtux.com Email: office@runtux.com
# All rights reserved
# ****************************************************************************
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# ****************************************************************************

from __future__       import print_function
import sys
from argparse         import ArgumentParser
from io               import BytesIO
from ooopy.OOoPy      import OOoPy
from ooopy.Transforms import OOo_Tag

def as_text (node, out, mimetype, newlines=False) :
    if node.text is not None :
        print (node.text, end = ' ', file = out)
    for subnode in node :
        as_text (subnode, out, mimetype, newlines)
    if node.tail is not None :
        print (node.tail, end = ' ', file = out)
    if newlines and node.tag == OOo_Tag ('text', 'p', mimetype) :
        print ("", file = out)


if __name__ == '__main__' :
    parser = ArgumentParser ()
    parser.add_argument \
        ( "file"
        , help    = "Input file(s) (defaults to stdin)"
        , nargs   = '*'
        )
    parser.add_argument \
        ( "-o", "--output-file"
        , dest    = "output_file"
        , help    = "Output file (defaults to stdout)"
        , default = None
        )
    parser.add_argument \
        ( "-n", "--newlines"
        , help    = "Add newlines after paragraphs"
        , action  = "store_true"
        )
    args = parser.parse_args ()
    if args.output_file is None :
        outfile = sys.stdout
    else :
        outfile = open (args.output_file, "w")
    if len (args.file) < 1 :
        infiles = [BytesIO (sys.stdin.read ())]
    else :
        infiles = args.file
    for f in infiles :
        o = OOoPy  (infile = f)
        e = o.read ('content.xml')
        as_text (e.getroot (), outfile, o.mimetype, args.newlines)
    print ()
