import logging

from common.status import (HTTP_400_BAD_REQUEST, HTTP_201_CREATED,
                           HTTP_405_METHOD_NOT_ALLOWED, HTTP_415_UNSUPPORTED_MEDIA_TYPE)
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from median.constant import TypeListe, EtatListe
from median.models import FListe, Magasin
from median.views import RiedlView
from peewee import DoesNotExist

riedl_taking_mode_blueprint = Blueprint('riedl_taking_mode', __name__)

logger = logging.getLogger('median')


@riedl_taking_mode_blueprint.route('', methods=['GET'])
@jwt_required()
def get():
    return {'message': 'ApiRiedlTakingMode::get not implemented'}, HTTP_405_METHOD_NOT_ALLOWED


@riedl_taking_mode_blueprint.route('', methods=['POST'])
@jwt_required()
def post():
    if not request.is_json:
        return {'message': 'Content-Type must be application/json'}, HTTP_415_UNSUPPORTED_MEDIA_TYPE

    content = request.get_json()

    liste = content.get('liste', 'test')
    lst = FListe.get(FListe.mode == TypeListe.Output.value, FListe.liste == liste)
    try:
        mag = Magasin.get(type_mag=lst.zone_fin)
    except DoesNotExist:
        err_message = "Riedl [%s] not found" % content.get('riedl', '')
        logger.error(err_message)
        return {'message': err_message}, HTTP_400_BAD_REQUEST

    if lst.etat != EtatListe.Solde.value:
        logger.error("List must be done")
        return {'message': "List must be done"}, HTTP_400_BAD_REQUEST

    if lst.id_peigne > 0:
        # Entry list already exists, we check if exists
        try:
            FListe.get(FListe.mode == TypeListe.Input.value, FListe.liste == lst.liste_origine)
            logger.error("Label list exists: %s" % lst.liste_origine)
            return {'message': "Label list exists: %s" % lst.liste_origine}, HTTP_400_BAD_REQUEST
        except DoesNotExist:
            logger.warning("List not exists anymore, we can recreate it: %s" % lst.liste_origine)

    rdlview = RiedlView(mag.type_mag)
    ret_id = rdlview.create_taking_mode(lst)

    return {'message': 'ApiRiedlTakingMode::get success', 'id': ret_id.pk}, HTTP_201_CREATED


@riedl_taking_mode_blueprint.route('', methods=['PUT'])
@jwt_required()
def put():
    return {'message': 'ApiRiedlTakingMode::put not implemented'}, HTTP_405_METHOD_NOT_ALLOWED


@riedl_taking_mode_blueprint.route('', methods=['DELETE'])
@jwt_required()
def delete():
    return {'message': 'ApiRiedlTakingMode::delete not implemented'}, HTTP_405_METHOD_NOT_ALLOWED
