import datetime
import json
import logging

from common.status import HTTP_400_BAD_REQUEST
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from median.constant import TypeListe, EtatListe, TypeServiListe, PatientGlobal
from median.models import FListe, Service, Magasin, FItem, Product
from peewee import DoesNotExist

from common.util import get_counter

global_output_blueprint = Blueprint('global_output_', __name__)

logger = logging.getLogger('median')


@global_output_blueprint.route('', methods=['GET'])
@jwt_required()
def get_all():
    return {'message': 'Use POST request!'}, HTTP_400_BAD_REQUEST


@global_output_blueprint.route('<string:ref>', methods=['GET'])
@jwt_required()
def get(ref):
    return {'message': 'Use POST request!'}, HTTP_400_BAD_REQUEST


@global_output_blueprint.route('<string:ref>', methods=['POST'])
@jwt_required()
def post(ref):
    logger.info("Sortie globale d'un produit : " + ref)

    args = json.loads(request.data)
    quantite_prelevee = args['quantite']
    poste = args['poste']
    service = args['service']
    # Verify is product exists, if not return 404
    try:
        Product.get(reference=ref)
    except DoesNotExist:
        return {'message': 'Product %s does not exists' % ref}, 404

    if quantite_prelevee is None or not isinstance(quantite_prelevee, int) or quantite_prelevee <= 0:
        return {'message': 'drugs.globaloutput.quantity.error'}, 500

    try:
        mag = Magasin.get(type_mag=poste)
        type_servi = TypeServiListe.GlobaleBoite.value
        if mag.eco_type == 'L':
            type_servi = TypeServiListe.RiedlBoite.value
    except DoesNotExist:
        return {'message': 'Warehouse relate to poste %s does not exists' % poste}, 404

    try:
        Service.get(code=service, type_dest='SERVICE')
    except DoesNotExist:
        return {'message': 'Service %s does not exists' % service}, 404

    number_item = 1
    try:
        lst = FListe.get(
            mode=TypeListe.Output.value, zone_deb="RIEDL",
            service=service, etat=EtatListe.Vierge.value, type_liste_web=1)
        number_item = lst.nb_item + 1
        lst.nb_item = number_item
        lst.type_servi = type_servi
        lst.date_modification = datetime.datetime.now()
        lst.save()
        logger.info("Draft lists %s exists, we add item on it" % lst.liste)
    except DoesNotExist:
        increment = get_counter("LIST_GLOBALE")
        lst = FListe()
        lst.liste = '%s-%s-%06d' % (mag.mag, service, int(increment))
        lst.mode = TypeListe.Output.value
        lst.etat = EtatListe.Vierge.value
        lst.zone_deb = 'RIEDL'
        lst.zone_fin = poste
        lst.fusion = "SORTIE GLOBALE"
        lst.num_sej = PatientGlobal.Sejour.value
        lst.ipp = PatientGlobal.Ipp.value
        lst.num_ipp = PatientGlobal.Ipp.value
        lst.service = service
        lst.type_servi = type_servi
        lst.no_pilulier = 1
        lst.pos_pilulier = 3
        lst.nb_item = 1
        lst.type_liste_web = 1
        lst.save()
        logger.warning("Not list exists we create a new one %s" % lst.liste)

    itm = FItem()
    itm.liste = lst.liste
    itm.mode = lst.mode
    itm.etat = EtatListe.Vierge.value
    itm.dest = lst.service
    itm.reference = ref
    itm.qte_dem = quantite_prelevee
    itm.qte_serv = 0
    itm.fraction = 100
    itm.type_servi = lst.type_servi
    itm.num_ipp = lst.num_ipp
    itm.num_sej = lst.num_sej
    itm.item = '%06d' % number_item
    itm.dtprise = datetime.datetime.now()
    itm.save()

    return {'result': "ok", 'id': lst.pk}
