import logging

from flask import Blueprint, request

from common.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from flask_jwt_extended import jwt_required
from median.models import Magasin, Stock

from peewee import fn

acced_batch_blueprint = Blueprint('acced_batch', __name__)

logger = logging.getLogger('median')


@acced_batch_blueprint.route('<string:batch>', methods=['GET'])
@jwt_required()
def get_by_batch(batch):
    try:
        ref = request.args.get('ref', None)
        ucd = request.args.get('ucd', None)
        req = (Magasin.select(Magasin.mag, Magasin.type_mag, Magasin.libelle, fn.SUM(Stock.quantite).alias('total'))
               .join(Stock, on=Magasin.mag == Stock.magasin)
               .where((Stock.lot == batch) &
                      (Magasin.eco_type == 'C') &
                      (Stock.reference == ref) &
                      (Stock.ucd == ucd))
               .group_by(Magasin.pk, Magasin.libelle))

        list = []
        for mag in req:
            obj = {
                "label": mag.libelle,
                "total": mag.total,
                "mag": mag.mag,
                'type_mag': mag.type_mag
            }
            list.append(obj)

        return {"list": list}, HTTP_200_OK

    except Exception as error:
        logger.error(error.args)
        return {'message': error.args}, HTTP_400_BAD_REQUEST
