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


import requests
from xml.dom.minidom import parse
import xml.dom.minidom


class LanguageParser:

    def parser(self, filename):
        result = {}
        domTree = xml.dom.minidom.parse(filename)
        collection = domTree.documentElement

        contexts = collection.getElementsByTagName('context')
        for context in contexts:

            name = context.getElementsByTagName('name')[0]
            name = name.childNodes[0].data
            print('name is %s' % name)

            languages = {}
            messages = context.getElementsByTagName('message')
            for message in messages:
                language = {}
                source = message.getElementsByTagName('source')[0]
                translation = message.getElementsByTagName('translation')[0]

                language['source'] = source.childNodes[0].data
                if translation.childNodes.length > 0:
                    language['translation'] = translation.childNodes[0].data
                else:
                    language['translation'] = ''

                # 取出location
                locations = []
                location_tags = message.getElementsByTagName('location')
                for location_tag in location_tags:
                    location = {}
                    filename = location_tag.getAttribute('filename')
                    line = location_tag.getAttribute('line')

                    if filename:
                        location['filename'] = filename
                    else:
                        location['filename'] = ''

                    if line:
                        location['line'] = line
                    else:
                        location['line'] = ''
                    locations.append(location)

                if len(locations) == 0:
                    locations.append({'filename': '', 'line': 0})
                language['locations'] = locations
                languages[language['source']] = language
            result[name] = {
                'name': name,
                'languages': languages
            }
        return result
