"""All path definitions for Subtitld"""


from bs4 import BeautifulSoup
from subtitld import timecode

# <?xml version="1.0" encoding="UTF-16"?>
USF_BASE_MARKUP = '''
<!-- USF file generated by Subtitld -->
<USFSubtitles version="1.0">
    <metadata></metadata>
    <styles></styles>
    <subtitles></subtitles>
</USFSubtitles>'''


class USFReader():
    """USFReader class"""
    def __init__(self, *args, **kwargs):
        super(USFReader, self).__init__(*args, **kwargs)

    def detect(self, content):
        """Function to return if this is a USF file"""
        if '<USFSubtitles' in content.lower():
            return True
        else:
            return False

    def read(self, content):
        """Function to return subtitles list"""
        subtitles_list = []

        soup = BeautifulSoup(content, features="lxml")
        for subtitles in soup.select("subtitles"):
            for element in subtitles:
                if element.name == 'subtitle':
                    subtitle = []
                    text = ''

                    for subelement in element:
                        if subelement.name in ['text', 'karaoke']:
                            text = subelement.text
                            continue

                    if 'start' in element.attrs and 'stop' in element.attrs and text:
                        subtitle.append(timecode.Timecode('1000', element.attrs['start']).float)
                        subtitle.append(timecode.Timecode('1000', element.attrs['stop']).float - timecode.Timecode('1000', element.attrs['start']).float)
                        subtitle.append(text.strip())

                    if subtitle:
                        subtitles_list.append(subtitle)

        return subtitles_list


class USFWriter():
    """USFWriter class"""
    def __init__(self, *args, **kwargs):
        super(USFWriter, self).__init__(*args, **kwargs)


    def write(self, subtitles):
        """Function to write subtitles, returns file content (XML)"""
        usf = BeautifulSoup(USF_BASE_MARKUP, 'lxml-xml')

        new_style = usf.new_tag('style')
        new_style['name'] = 'Default'
        new_fontstyle = usf.new_tag('fontstyle', color='#EEEEFF', face='Arial', size='24', family='Arial')
        new_fontstyle['outline-color'] = '#5555FF'
        new_style.append(new_fontstyle)
        new_position = usf.new_tag('position', alignment='BottomCenter')
        new_position['relative-to'] = 'Window'
        new_position['vertical-margin'] = '10%'
        new_style.append(new_position)
        usf.find('styles').append(new_style)

        for subtitle in subtitles:
            new_sub = usf.new_tag('subtitle', start=str(timecode.Timecode('1000', start_seconds=subtitle[0], fractional=True)), stop=str(timecode.Timecode('1000', start_seconds=subtitle[1] + subtitle[0], fractional=True)))
            new_text = usf.new_tag('text')
            new_text.string = subtitle[2]
            new_sub.append(new_text)
            usf.find('subtitles').append(new_sub)

        return str(usf.prettify())
