# -*- coding: utf-8 -*-
"""
Транспорт для интефакса
"""
import json
import requests
from stocks3.core.factories import transports
from stocks3.core.transport import Transport
from stocks3.core.config import JSONConfigurable
from stocks3.core.utils import force_decode
from datetime import datetime
from datetime import timedelta


class IntefaxTransport(Transport, JSONConfigurable):
    """
    """

    def __init__(self, tree, node, source):
        Transport.__init__(self, tree, node, source)
        self.auth_file = self.readString("query", "authfile", '') or None
        if self.auth_file is not None:
            JSONConfigurable.__init__(self, configfile=self.auth_file)
            self.username = self.read_item("interfax.user", '')
            self.password = self.read_item("interfax.password", '')

    def transfer(self, place):
        Transport.transfer(self, place)

        # stage 1 - auth
        r = requests.post(
            "https://new-datahub.efir-net.ru/hub.axd/Account/Login",
            headers={"Content-Type": "application/json", "Accept": "application/json"},
            data=json.dumps({'login': self.username, 'password': self.password}),
            # verify=False
        )
        if r.status_code != 200:
            raise IOError('Bad status from intefax - {0} : {1}'.format(r.status_code, r.content))
        content = force_decode(r.content)
        result = json.loads(content)

        # stage 2 - getting data
        token = result['Token']
        date_from = (datetime.now() - timedelta(minutes=20)).strftime("%Y-%m-%dT%H:%M:00.0000000Z")
        date_to = datetime.now().strftime("%Y-%m-%dT%H:%M:00.0000000Z")

        r = requests.get(
            "https://new-datahub.efir-net.ru/hub.axd/Archive/History",
            params={
                "issId": 831776,
                "step": 1,
                "dateFrom": date_from,
                "dateTo": date_to,
                "fields": "TIME,AVGE_PRCE",
                "token": token
            },
            headers={"Content-Type": "application/json", "Accept": "application/json"},
        )

        if r.status_code != 200:
            raise IOError('Bad status from intefax - {0} : {1}'.format(r.status_code, r.content))

        place.store(r.content)  # Регистрируем транспорты


transports.register("stocks3.transports.interfax", IntefaxTransport)
