#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#==============================================================================
# Copyright (C) 2011 by Loïc Grobol
#
# This file is part of CTESLO.
# 
#    CTESLO is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
# 
#    CTESLO 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 General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with CTESLO.  If not, see <http://www.gnu.org/licenses/>.
#==============================================================================

"""
Created on 28 oct. 2011

@author: Loïc Grobol <loic.grobol@gmail.com>
"""

import argparse, sys
import xml.etree.ElementTree as etree


def get_internal_text(tag):
    def get_texts(child):
        text = child.text.strip("\n ") if child.text is not None else ""
        if child.tail: text = "{0} {1}".format(text, child.tail.strip("\n ")) if text else child.tail.strip("\n ")
        if child.tag=="Who": text += "\n"
        return text

    texts = [get_texts(child) for child in tag.getiterator()]
    final_text = tag.text.strip("\n ") + "\n".join([text for text in texts if text])
    return final_text.strip("\n ")

def clean_stream(in_stream, out_stream):
    parser = etree.XMLParser(encoding="utf-8")
    tree = etree.parse(in_stream, parser=parser)
    root = tree.getroot()
    turns = root.findall(".//Turn")
    for turn in turns:
        text = get_internal_text(turn)
        if text:
            out_stream.write("{0}\n".format(text))


def main(argv=sys.argv[1:]):
    """Main function."""
    parser = argparse.ArgumentParser(description="Get speech turns from trs files.")
    parser.add_argument("--in-stream", "-i",
                         type=argparse.FileType('r'),
                         default=sys.stdin,
                         help="trs file to be formated. Standard input by default.")
    parser.add_argument("--out-stream", "-o",
                         type=argparse.FileType('w'),
                         default=sys.stdout,
                         help="Text file to be written. Standard output by default.")
    args = parser.parse_known_args(argv)[0] # Get only known args
    if args.in_stream.isatty():
        parser.print_help()
    else:
        clean_stream(args.in_stream, args.out_stream)

if __name__ == "__main__":
    sys.exit(main())
