import json
import logging

from flask import Blueprint, jsonify, request

from .auth import token_required
from ..factory import get_provider

bp = Blueprint('wsgi', __name__)
logger = logging.getLogger(__name__)


@bp.route('/home')
def page_home():
    return "Base wsgi"


@bp.route('/api', methods=["GET", 'POST'])
@token_required
def page_api():
    print("dbg", dir(request))
    print("dbg args", request.args)
    print("dbg form", request.form)
    print("dbg json", request.json)
    data = "a" * 100  # open("rac5_hourly.csv").read()
    return jsonify({"status": "success", "message": "valid token", "data": data})


@bp.route('/api/<provider>', methods=['POST'])
@token_required
def page_api_provider(provider):
    logger.info("api provider %s with params %s", provider, json.dumps(request.json))
    try:
        prov_mod = get_provider(provider)
        prov = prov_mod.Provider()
    except Exception as err:
        logger.info("error provider: %s", err)
        raise err
    try:
        df, header = prov.get(**request.json)
    except Exception as err:
        logger.info("error fetch: %s", err)
        raise err
    return jsonify({"status": "success",
                    "message": "valid token",
                    "data": df.to_csv(None, sep=";"),
                    "header": header,
                    })
