import datetime
import logging

from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from median.constant import TypeServiListe, PatientGlobal, TypeListe, EtatListe
from median.models import FListe, FItem, Patient, Sejour
from peewee import DoesNotExist

global_blueprint = Blueprint('global', __name__)

logger = logging.getLogger('median')


@global_blueprint.route('', methods=['POST'])
@jwt_required()
def create_global():
    args = request.json
    service = args['service']
    ref = args['ref']
    quantite = args['quantite']
    fraction = args['fraction']

    liste = '%s GLOBALE %s' % (datetime.date.today().strftime("%Y-%m-%d"), service)

    # Check if global patient exists and episode
    try:
        Patient.get(ipp=PatientGlobal.Ipp.value)
    except DoesNotExist:
        p = Patient()
        p.ipp = PatientGlobal.Ipp.value
        p.prenom = 'GL'
        p.nom = 'GL'
        p.sexe = 'H'
        p.save()

        s = Sejour()
        s.ipp = p.ipp
        s.sejour = PatientGlobal.Sejour.value
        s.save()

    # Check if liste is already exists
    try:
        d = FListe.get(liste=liste)

    except DoesNotExist:
        d = FListe(
            liste=liste,
            date_creation=datetime.datetime.now(),
            mode=TypeListe.Output.value,
            etat=EtatListe.Vierge.value,
            fusion='SORTIE GLOBALE BOITE PASS',
            service=service,
            nb_item=1,
            date_modification=datetime.datetime.now(),
            type_servi=TypeServiListe.GlobaleBoite.value,
            id_servi=2,
            num_ipp=PatientGlobal.Ipp.value,
            num_sej=PatientGlobal.Sejour.value,
        )
        d.save()

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

    try:
        # Create f_item
        paged_item = FItem.select(FItem.item).where(FItem.liste == liste).order_by(FItem.item.desc())

        if len(paged_item) == 0:
            item = "000001"
        else:
            item = int(paged_item[0].item) + 1

        itm = FItem(
            liste=liste,
            reference=ref,
            mode=TypeListe.Output.value,
            etat=EtatListe.Vierge.value,
            item=str(item).zfill(6),
            qte_dem=quantite,
            fraction=fraction,
            dest=service,
            type_servi=TypeServiListe.GlobaleBoite.value,
            id_servi=2,
            num_ipp=PatientGlobal.Ipp.value,
            num_sej=PatientGlobal.Sejour.value,
        )
        itm.save()
    except Exception as error:
        logger.error(error.args)
        return {'message': error.args}, 400

    d.date_modification = datetime.datetime.now()
    d.save()

    return {"result": "ok", "id": d.pk}
