# -*- coding: utf-8 -*-

"""
Генерирует XML-файл для заливки в танкер.

В танкер попадают только те котировки, которые экспортируются в XML.

Этот скрипт пробегается по всем котировкам, смотрит, у каких котировок стоит
флажок item и гонит эти котировки в tanker.

На выходе скрипта появляется файлик:
        <?xml version="1.0" encoding="utf-8"?>
        <tanker>
            <project id="stocks">
                <keyset id="main">
                    <keyset is_plural="False" id="id.name | id.news_title">
                      <value status="approved" language="?">value</value>
                    </keyset>
                </keyset>
            </project>
        </tanker>
"""

import sys
import string
import os
import json
sys.path.append(".")
from stocks3.core.config import parse_xml
from stocks3.core.config import etree


TANKER_PROJECT_ID = "stocks"
TANKER_KEYSET = "main"
TANKER_SOURCES_KEYSET = "sources"
LANGUAGES = ["ru", "en", "uk", "be", "tt", "kk", "hy", "tr"]
# Если значение не ASCII, то считаем его русским.
NOTASCII_LANGUAGES = ["ru"]
SOURCES_PATH = "./catalog/sources/"


def is_ascii(s):
    return all(c in string.printable for c in s)


class L10NQuoteInfo(object):
    def __init__(self, quote_id, export_name, l10n_name, news_title, page_title, page_desc, index_title, line_titles):
        """
        @param quote_id: идентификатор котировки (числовой);
        @param export_name: экспортное имя;
        @param l10n_name: еще одно имя (опциональное);
        @param news_title: заголовок для новостей;
        @param line_titles: подписи для графиков (словарь вида: line_id =>
                            word);
        """
        self.quote_id = quote_id
        self.export_name = export_name
        self.l10n_name = l10n_name
        self.news_title = news_title
        self.page_title = page_title
        self.page_desc = page_desc
        self.index_title = index_title
        self.line_titles = line_titles

    def get_name(self):
        if len(self.l10n_name) != 0:
            return self.l10n_name
        else:
            return self.export_name

    @staticmethod
    def _make_values(key, name):
        if is_ascii(name):
            languages = LANGUAGES
        else:
            languages = NOTASCII_LANGUAGES
        for language in languages:
            value = etree.SubElement(key, "value")
            value.attrib["status"] = "approved"
            value.attrib["language"] = language
            value.text = name

    def attach_node(self, root, suffix, name):
        key = etree.SubElement(root, "key")
        key.attrib["is_plural"] = "False"
        key.attrib["id"] = str(self.quote_id) + suffix
        self._make_values(key, name)

    def attach_name(self, root):
        self.attach_node(root, ".name", self.get_name())

    def attach_news_title(self, root):
        self.attach_node(root, ".news_title", self.news_title)

    def attach_page_title(self, root):
        self.attach_node(root, ".page_title", self.page_title)

    def attach_page_desc(self, root):
        self.attach_node(root, ".page_desc", self.page_desc)

    def attach_index_title(self, root):
        self.attach_node(root, ".index_title", self.index_title)

    def attach_line_titles(self, root):
        """
        Подписи для рядов графиков хранятся в ключах с именем: id.line.line_id.
        """
        for line_id, name in list(self.line_titles.items()):
            suffix = ".line_title.%s" % line_id
            self.attach_node(root, suffix, name)

    def attach(self, root):
        self.attach_name(root)
        if len(self.news_title) != 0:
            self.attach_news_title(root)
        if self.page_title is not None and len(self.page_title) != 0:
            self.attach_page_title(root)
        if self.page_desc is not None and len(self.page_desc) != 0:
            self.attach_page_desc(root)
        if self.index_title is not None and len(self.index_title) != 0:
            self.attach_index_title(root)
        self.attach_line_titles(root)


def get_line_titles(quote):
    """
    Выдирает из определения котировки подписи для графиков.
    @:param quote
    """
    return quote.get('lines', {})


def add_source_key(root, source_id, source_text):
    key = etree.SubElement(root, "key")
    key.attrib["is_plural"] = "False"
    key.attrib["id"] = str(source_id)
    value = etree.SubElement(key, "value")
    value.attrib["status"] = "approved"
    value.attrib["language"] = 'ru'
    value.text = source_text
    pass


def get_sources_descriptions(root):
    for i in os.listdir(SOURCES_PATH):
        source = parse_xml(SOURCES_PATH + i)
        source_id = int(source.getroot().attrib['inner-id'])
        source_text = source.find('name').text
        if (source_id != 999) and (source_text is not None):
            add_source_key(root, source_id, source_text)
    pass


def main():
    with open("catalog/quotes.json") as fp:
        quotes = json.load(fp)

    tanker = etree.Element("tanker")
    project = etree.SubElement(tanker, "project")
    project.attrib["id"] = TANKER_PROJECT_ID
    keyset = etree.SubElement(project, "keyset")
    keyset.attrib["id"] = TANKER_KEYSET
    quotes_info = {}

    for quote in quotes:
        quote_id = quote.get('id')
        export_name = quote.get('export-name', '')
        news_title = quote.get('news-title', '')
        page_title = quote.get('page-title', '')
        page_desc = quote.get('page-description', '')
        index_title = quote.get('index-title', '')

        l10n_name = quote.get('l10n-name', '')
        line_titles = get_line_titles(quote)

        info = L10NQuoteInfo(quote_id, export_name, l10n_name, news_title, page_title, page_desc, index_title,
                             line_titles)
        info.attach(keyset)

    sources_keyset = etree.SubElement(project, "keyset")
    sources_keyset.attrib["id"] = TANKER_SOURCES_KEYSET

    get_sources_descriptions(sources_keyset)

    print('<?xml version="1.0" encoding="utf-8"?>')
    print(etree.tounicode(tanker, pretty_print=True))
    # print(etree.tostring(tanker, pretty_print=True, encoding="utf-8"))


if __name__ == "__main__":
    main()
