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

from utility.FileGetter import FileGetter
from utility.XMLProtocol import XMLProtocol
import configparser
from tqdm import tqdm


def beautify_xml(case, alter_lines=False, line_width=0):
    """
    Beautifies the xml protocols so that they are easily readable by humans.
    Uses .beautify_xml_part() and .beautify_xml() to be able to format lines for
    specific parts of an xml. Alter lines can be set to Flase or True. Line
    width that will be used if alter_lines is True can be set to any value
    between 0 and 160.
    """
    config = configparser.ConfigParser()
    config.read("config.ini")
    if(case == "markup"):
        output_path = config["File paths"]["output_folder"]
        input_path = config["File paths"]["clear_speech_markup"]
        key_name = "beautiful_xml"
    elif(case == "nlp"):
        output_path = config["File paths"]["nlp_output"]
        input_path = config["File paths"]["nlp_lemmatized_tokenized"]
        key_name = "nlp_beuatiful_xml"
    files = FileGetter(input_path, "*.xml")
    files = files.get_files()
    for file_path in tqdm(sorted(files), desc="First beautification steps"):
        xml = XMLProtocol()
        xml.read_xml(file_path)
        xml.beautify_xml_part(file_path, ".//vorspann")
        xml.replace_elements(".//vorspann", [xml.beautified_part])
        xml.beautify_xml_part(file_path, ".//sitzungsverlauf", alter_lines,
                              line_width)
        xml.replace_elements(".//sitzungsverlauf", [xml.beautified_part])
        xml.save_to_file(output_path, file_path, key_name,
                         "File paths", key_name)
    config.read("config.ini")
    beautiful_xmls_path = config["File paths"][key_name]
    files = FileGetter(beautiful_xmls_path, "*.xml")
    files = files.get_files()
    for file_path in tqdm(files, desc="Second beautification steps"):
        xml.beautify_xml(file_path, False)


if __name__ == '__main__':
    beautify_xml()
