import csv
import os

import pkg_resources

from flask import Blueprint, jsonify, current_app
from inventory_provider.routes import common
from inventory_provider.tasks.common import get_current_redis, get_latch

routes = Blueprint("inventory-data-default-routes", __name__)

API_VERSION = '0.1'

VERSION_SCHEMA = {
    "$schema": "http://json-schema.org/draft-07/schema#",

    "definitions": {
        "latch": {
            "type": "object",
            "properties": {
                "current": {"type": "integer"},
                "next": {"type": "integer"},
                "this": {"type": "integer"},
                "failure": {"type": "boolean"},
                "pending": {"type": "boolean"},
            },
            "required": ["current", "next", "this", "pending", "failure"],
            "additionalProperties": False
        }
    },

    "type": "object",
    "properties": {
        "api": {
            "type": "string",
            "pattern": r'\d+\.\d+'
        },
        "module": {
            "type": "string",
            "pattern": r'\d+\.\d+'
        },
        "latch": {"$ref": "#/definitions/latch"}
    },
    "required": ["api", "module"],
    "additionalProperties": False
}


@routes.after_request
def after_request(resp):
    return common.after_request(resp)


@routes.route("/version", methods=['GET', 'POST'])
@common.require_accepts_json
def version():
    """
    Returns a json object with information about the module version.

    The response will be formatted according to the following schema:

    .. asjson:: inventory_provider.routes.default.VERSION_SCHEMA

    :return:
    """
    config = current_app.config["INVENTORY_PROVIDER_CONFIG"]
    version_params = {
        'api': API_VERSION,
        'module':
            pkg_resources.get_distribution('inventory_provider_ims').version
    }
    latch = get_latch(get_current_redis(config))
    if latch:
        version_params['latch'] = latch
    return jsonify(version_params)