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

import sys
import string
import os
import json
sys.path.append(".")
from pprint import pprint
from yt.wrapper import YtClient
from stocks3.core.config import JSONConfigurable
from stocks3.core.common import get_field

OUTPUT_FOLDER = "//home/morda/stocks/"


class YtSaver(JSONConfigurable):
    def __init__(self):
        JSONConfigurable.__init__(self)
        self.yt_token = self.read_item("yt_token", "")
        self.yt_client = YtClient(proxy="hahn", config={"tabular_data_format": "json"}, token=self.yt_token)

    def save_translations(self, translations_data):
        output_table = OUTPUT_FOLDER + "translations"
        result = []
        for quote_id, data in translations_data.items():
            for key, data in data.items():
                for lang, value in data.items():
                    if value is not None:
                        result.append({
                            "quote_id": int(quote_id),
                            "key": key,
                            "lang": lang,
                            "translation": value,
                        })
        schema = [
            {"name": "quote_id", "type": "uint32"},
            {"name": "key", "type": "string"},
            {"name": "lang", "type": "string"},
            {"name": "translation", "type": "string"},
        ]

        if self.yt_client.exists(output_table):
            self.yt_client.remove(output_table)
        self.yt_client.create("table", output_table, attributes={"schema": schema})
        self.yt_client.write_table(output_table, result)
        print("success write table:", output_table)

    def save_sources(self, sources_data):
        output_table = OUTPUT_FOLDER + "sources"
        result = []
        for lang, data in sources_data.items():
            for source_id, translation in data["sources"].items():
                result.append({
                    "source_id": int(source_id),
                    "lang": lang,
                    "translation": translation,
                })

        schema = [
            {"name": "source_id", "type": "uint32"},
            {"name": "lang", "type": "string"},
            {"name": "translation", "type": "string"},
        ]
        if self.yt_client.exists(output_table):
            self.yt_client.remove(output_table)
        self.yt_client.create("table", output_table, attributes={"schema": schema})
        self.yt_client.write_table(output_table, result)
        print("success write table:", output_table)

    def save_quotes_info(self, quotes):
        output_table = OUTPUT_FOLDER + "quotes"
        result = []
        for quote in quotes:
            result.append({
                "quote_id": int(quote.get("id")),
                "name": quote.get("name", ""),
                "numerator": get_field(quote, "numerator.stock", safe=True, default=""),
                "denominator": get_field(quote, "denominator.stock", safe=True, default=""),
                "export-name": quote.get("export-name", ""),
                "news-title": quote.get("news-title", ""),
                "name-readable": quote.get("name-readable", ""),
                "page-title": quote.get("page-title", ""),
                "page-description": quote.get("page-description", ""),
                "index-title": quote.get("index-title", ""),
                "comment": quote.get("comment", ""),
            })

        schema = [
            {"name": "quote_id", "type": "uint32"},
            {"name": "name", "type": "string"},
            {"name": "numerator", "type": "string"},
            {"name": "denominator", "type": "string"},
            {"name": "export-name", "type": "string"},
            {"name": "news-title", "type": "string"},
            {"name": "name-readable", "type": "string"},
            {"name": "page-title", "type": "string"},
            {"name": "page-description", "type": "string"},
            {"name": "index-title", "type": "string"},
            {"name": "comment", "type": "string"},
        ]
        if self.yt_client.exists(output_table):
            self.yt_client.remove(output_table)
        self.yt_client.create("table", output_table, attributes={"schema": schema})
        self.yt_client.write_table(output_table, result)
        print("success write table:", output_table)


def main():
    yt_saver = YtSaver()
    try:
        with open("data/l10n/index.json") as index:
            translations_data = json.load(index)
            yt_saver.save_translations(translations_data)

        with open("data/l10n/news/sources.json") as sources:
            sources_data = json.load(sources)
            yt_saver.save_sources(sources_data)

        with open("catalog/quotes.json") as fp:
            quotes = json.load(fp)
            yt_saver.save_quotes_info(quotes)

    except IOError:
        print("Cannot find files data/l10n/index.json and data/l10n/news/sources.json")
        print("Need to download translation ( ./tanker/download-from-production.sh )")


if __name__ == "__main__":
    main()
