# coding: utf-8
from __future__ import absolute_import

from spyne.decorator import rpc
from spyne.model.primitive import String

from . import utils
from .types import BuildIndexResponse
from .types import GetBuildedIndexResponse
from .types import GetIndexResponse
from .types import IndexPeriod


@rpc(
    String, String, IndexPeriod,
    _in_variable_names=dict(
        report_code='IndexCode',
        param='IndexParam',
        period='IndexPeriod',
    ),
    _returns=GetIndexResponse,
    _out_message_name='GetIndexResponse',
)
def GetIndexRequest(ctx, report_code, param, period):
    # Формирование и возврат данных.

    from ..data import utils as data_utils
    assert isinstance(period, IndexPeriod), type(period)

    utils.validate_request(ctx, report_code, period)
    content_params = utils.create_content_params(
        ctx, report_code, param, period
    )

    out_format = 'xml'
    file_name = '.'.join((report_code, out_format))
    content = data_utils.get_content(**content_params)

    return GetIndexResponse.create(file_name, content)


@rpc(
    String, String, IndexPeriod,
    _in_variable_names=dict(
        report_code='IndexCode',
        param='IndexParam',
        period='IndexPeriod',
    ),
    _returns=BuildIndexResponse,
    _out_message_name='BuildIndexResponse',
)
def BuildIndexRequest(ctx, report_code, param, period):
    # Асинхронное формирование данных и возврат идентификатора запроса.

    from ..data import tasks as data_tasks
    assert isinstance(period, IndexPeriod), type(period)

    utils.validate_request(ctx, report_code, period)

    out_format = 'xml'
    file_name = '.'.join((report_code, out_format))
    report_uid = utils.create_report_uid()

    # ctx не передается, т.к. возможны трудности сериализации
    content_params = utils.create_content_params(
        None, report_code, param, period, report_uid, file_name
    )

    data_tasks.async_create_content(**content_params)

    return BuildIndexResponse.create(report_uid)


@rpc(
    String,
    _in_variable_names=dict(
        report_uid='IndexIdent',
    ),
    _returns=GetBuildedIndexResponse,
    _out_message_name='GetBuildedIndexResponse',
)
def GetBuildedIndexRequest(ctx, report_uid):
    # Проверка и возврат сформированных данных по идентификатору.

    from ..data import utils as data_utils

    utils.validate_get_builded_index_request(ctx, report_uid)

    file_name, content = data_utils.get_content_by_ident(ctx, report_uid)

    return GetBuildedIndexResponse.create(file_name, content)
