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

from markup.SpeakerNameMarkup import SpeakerNameMarkup
from markup.MdBData import MdBData
from utility.FileGetter import FileGetter
from xml.etree import ElementTree
from tqdm import tqdm
import os
import configparser
import logging


def get_names():
    """
    This script gets the identified speaker elements. It will analyse the text
    of those to determine <vorname>, <nachname>, @id etc. for every speaker.
    Also creates a speech id for every speech.
    """
    ###
    # Setting paths in config and start logging
    ###
    logger = logging.getLogger(__name__)
    config = configparser.ConfigParser()
    config.read("config.ini")
    xml_path = config["File paths"]["new_simple_markup"]
    output_path = config["File paths"]["output_folder"]
    parent_path = os.path.dirname(os.getcwd())
    stammdatenbank_full_path = os.path.join(parent_path,
                                            "data/MdB_data/MdB_Stammdaten.xml")
    ###
    # opens and reads Stammdatenbank
    ###
    stammdatenbank = MdBData()
    stammdatenbank.read_xml(stammdatenbank_full_path)
    ###
    # Getting sets of different name name/MdB features
    ###
    # getting first names
    first_names = stammdatenbank.get_set(".//VORNAME", stammdatenbank.xml_tree)
    first_names.discard(None)
    # getting las names
    last_names = stammdatenbank.get_set(".//NACHNAME", stammdatenbank.xml_tree)
    last_names.discard(None)
    # getting academic titles
    academic_titles = stammdatenbank.get_set(".//AKAD_TITEL",
                                             stammdatenbank.xml_tree)
    academic_titles_short = stammdatenbank.get_set(".//ANREDE_TITEL",
                                                   stammdatenbank.xml_tree)
    additional_academic_titles = [title for title in config["Additional name features"]["academic_titles"].split()]
    for title in additional_academic_titles:
        academic_titles.add(title)
    academic_titles = academic_titles.union(academic_titles_short)
    academic_titles.discard(None)
    # getting parties
    parties = stammdatenbank.get_set(".//PARTEI_KURZ", stammdatenbank.xml_tree)
    additional_parties = [party for party in config["Additional name features"]["parties"].split()]
    for party in additional_parties:
        parties.add(party)
    parties.discard(None)
    # getting name affixes
    name_affixes = stammdatenbank.get_set(".//PRAEFIX", stammdatenbank.xml_tree)
    name_affixes.discard(None)
    # getting cities
    cities = stammdatenbank.get_set(".//ORTSZUSATZ", stammdatenbank.xml_tree)
    cities.discard(None)
    # setting empty sets to later combine them with XML node names for XPaths
    party = set()  #
    periode = set()  #
    feature_complete = set()  #
    speaker_id = set()  #
    role_long = set()
    role_short = set()
    ###
    # creating dict with tuples of sets and corresponding XML node name
    ###
    sets = [(first_names, "VORNAME"), (last_names, "NACHNAME"),
            (academic_titles, "AKAD_TITEL"), (parties, "PARTEI_KURZ"),
            (name_affixes, "PRAEFIX"), (cities, "ORTSZUSATZ"),
            (party, "PARTEI_KURZ"), (periode, "WP"), (feature_complete, "None"),
            (speaker_id, "ID"), (role_long, "None"), (role_short, "None")]
    features = ["vorname", "nachname", "titel", "fraktion", "namenszusatz",
                "ortszusatz", "partei", "wahlperiode", "feature_complete",
                "id", "rolle_lang", "rolle_kurz"]
    feature_set_dict = dict(zip(features, sets))
    ###
    # opening XML protocolls
    # starting speaker markup for features
    ###
    files = FileGetter(xml_path, "*.xml")
    files = files.get_files()
    for file_path in tqdm(sorted(files),
                          desc="File status"):
        complex_speaker = SpeakerNameMarkup(file_path, ".//redner")
        complex_speaker.read_xml(file_path)
        complex_speaker.get_element_text()
        logger.info(("Doing cross reference markup for names to get redner ids."
                     + " For file: "
                     + os.path.basename(file_path)))
        complex_speaker.cross_reference_markup(complex_speaker.current_strings,
                                               feature_set_dict,
                                               stammdatenbank.xml_tree)
        complex_speaker.create_speaker_elements()
        complex_speaker.replace_elements(".//redner",
                                         complex_speaker.all_speaker_elements,
                                         True)
        xml_string = ElementTree.tostring(complex_speaker.xml_tree)
        bool = complex_speaker.simple_check_xml(xml_string, file_path, False,
                                                False)
        if(bool is False):
            logger.error(("This XML file is not well-formed. Program stopped."
                          " Fix or remove this file an run the program again."
                          ))
            print("Program has stopped. See logs for more info.")
            break
        complex_speaker.set_speech_ids()
        complex_speaker.save_to_file(output_path, file_path, "complex_markup",
                                     "File paths", "complex_markup")


if __name__ == '__main__':
    get_names()
