import logging

from flask import Blueprint, jsonify

from compendium_v2.routes import common
from compendium_v2.db.model import TrafficVolume
from typing import Any


routes = Blueprint('traffic', __name__)
logger = logging.getLogger(__name__)

TRAFFIC_RESPONSE_SCHEMA = {
    '$schema': 'http://json-schema.org/draft-07/schema#',

    'definitions': {
        'traffic': {
            'type': 'object',
            'properties': {
                'nren': {'type': 'string'},
                'nren_country': {'type': 'string'},
                'year': {'type': 'integer'},
                'to_customers': {'type': 'number'},
                'from_customers': {'type': 'number'},
                'to_external': {'type': 'number'},
                'from_external': {'type': 'number'}
            },
            'required': ['nren', 'nren_country', 'year', 'to_customers',
                         'from_customers', 'to_external', 'from_external'],
            'additionalProperties': False
        }
    },

    'type': 'array',
    'items': {'$ref': '#/definitions/traffic'}
}


@routes.route('/', methods=['GET'])
@common.require_accepts_json
def traffic_volume_view() -> Any:
    """
    handler for /api/traffic/ requests

    response will be formatted as:

    .. asjson::
        compendium_v2.routes.traffic.TRAFFIC_RESPONSE_SCHEMA

    :return:
    """

    def _extract_data(entry: TrafficVolume):
        return {
            'nren': entry.nren.name,
            'nren_country': entry.nren.country,
            'year': entry.year,
            'to_customers': float(entry.to_customers),
            'from_customers': float(entry.from_customers),
            'to_external': float(entry.to_external),
            'from_external': float(entry.from_external)
        }

    entries = sorted(
        [_extract_data(entry) for entry in common.get_data(TrafficVolume)],
        key=lambda d: (d['nren'], d['year'])
    )
    return jsonify(entries)