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

"""
Модуль проверяет значения по календарю - позволяет проходить котировкам только в рабочие дни (по россии)
"""
from stocks3.core.checker import Checker
from stocks3.core.factories import checkers
from stocks3.core.config import str_to_bool
from stocks3.share.curl import load_url_data
from datetime import timedelta, datetime
from stocks3.share import messages
import json

__author__ = "Bogdanov Evgeny"
__email__ = "evbogdanov@yandex-team.ru"


class CalendarChecker(Checker):
    """
    Проверяет новое значение на пригодность.

    """

    def __init__(self, tree, node, source):
        Checker.__init__(self, tree, node, source)
        self.dates = {}
        # self._quotes_for_skip_weekends = {}

    def makeConfig(self):
        self._load_ids_checks()
        return self

    def _load_ids_checks(self):
        """
        Загружает ограничения для конкретных котировок.
        Обрабатывает элементы checkers/checker.
        """
        self._ids_checks = {}
        self._quotes_for_skip_weekends = {}
        for checkNode in self.node.findall("check"):
            if "onlyweekdays" in checkNode.attrib:
                self._ids_checks[checkNode.attrib["quote"]] = str_to_bool(checkNode.attrib["onlyweekdays"])
            if "skip_weekends" in checkNode.attrib:
                self._quotes_for_skip_weekends[checkNode.attrib["quote"]] = str_to_bool(checkNode.attrib["skip_weekends"])

    @staticmethod
    def get_date_info(datestring):
        url = "https://api.calendar.yandex-team.ru/intapi/get-holidays?from={0}&to={1}" \
              "&outMode=all&for=225&who_am_i=home.stocks".format(datestring, datestring)
        data = load_url_data(url).decode("utf8")
        data = json.loads(data)
        return data["holidays"][0]["type"] not in ["holiday", "weekend"]

    def perform_check(self, date):
        datestring = str(date.date() - timedelta(1))
        if datestring not in self.dates:
            self.dates[datestring] = self.get_date_info(datestring)
        return self.dates[datestring]

    @staticmethod
    def perform_check_skip_weekends(date: datetime):
        return date.weekday() > 4

    def check(self, price):
        """
        Получает дату котировки и выполняет проверку.
        """
        try:
            quotename = self.source.default.quotes_config.get_quote_name(price.quote.quote_id)

            if quotename in self._quotes_for_skip_weekends and self._quotes_for_skip_weekends[quotename]:
                if self.perform_check_skip_weekends(price.date):
                    return False

            if quotename in list(self._ids_checks.keys()):
                if self._ids_checks[quotename]:
                    return self.perform_check(price.date)
            return True
        except Exception as e:
            messages.error("ERROR IGNORED: Calendar: %s" % (str(e)))
            return True


checkers.register("stocks3.checkers.Calendar", CalendarChecker)
