import json
import logging

from common.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_204_NO_CONTENT
from flask import Blueprint, request, send_file
from flask_jwt_extended import jwt_required
from median.models import Magasin
from ressources.astus.consumption.astus_consumption_service import get_consumption, get_obj_consumption, \
    lock_comsumption_replenish
from ressources.astus.utils import generate_memory_excel_file

astus_consumption_blueprint = Blueprint('astus_consumption', __name__)

logger = logging.getLogger('median')


@astus_consumption_blueprint.route('<string:pk>', methods=['POST'])
@jwt_required()
def get_by_mag(pk):
    try:
        data = json.loads(request.data)

        equipment = Magasin.select(Magasin.type_mag).where(Magasin.pk == pk).get()

        list_conso = get_consumption(type_mag=equipment.type_mag, data=data)

        return {'list': [get_obj_consumption(m) for m in list_conso]}, HTTP_200_OK

    except Exception as error:
        logger.error(error.args)
        return {
            'alertMessage': 'astus.consumption.error',
            'param': [pk]
        }, HTTP_500_INTERNAL_SERVER_ERROR


@astus_consumption_blueprint.route('<string:pk>/export', methods=['PATCH'])
@jwt_required()
def export(pk):
    data = json.loads(request.data)
    headers = data.get('headers', [])
    equipment = Magasin.select(Magasin.type_mag).where(Magasin.pk == pk).get()
    lines = get_consumption(equipment.type_mag, data)
    memory_file = generate_memory_excel_file(headers=headers, items=lines, transform_function=get_obj_consumption)

    return send_file(memory_file, as_attachment=True, download_name="consumption.xlsx")


@astus_consumption_blueprint.route('<string:equipment_pk>/unlock', methods=['PUT'])
@jwt_required()
def unlock_replenish(equipment_pk):
    data = json.loads(request.data)
    references = data.get('references_pk', [])
    try:
        lock_comsumption_replenish(equipment_pk, references, False)

        return {}, HTTP_204_NO_CONTENT

    except Exception as error:
        logger.error(error.args)
        return {
            'alertMessage': 'astus.consumption.error',
        }, HTTP_500_INTERNAL_SERVER_ERROR


@astus_consumption_blueprint.route('<string:equipment_pk>/lock', methods=['PUT'])
@jwt_required()
def lock_replenish(equipment_pk):
    try:
        data = json.loads(request.data)
        references = data.get('references_pk', [])
        lock_comsumption_replenish(equipment_pk, references, True)

        return {}, HTTP_204_NO_CONTENT

    except Exception as error:
        logger.error(error.args)
        return {
            'alertMessage': 'astus.consumption.error',
        }, HTTP_500_INTERNAL_SERVER_ERROR
