import logging

from common.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR
from flask import Blueprint
from flask_jwt_extended import jwt_required
from median.models import Ucd, Product

gtin_blueprint = Blueprint('gtin', __name__)

logger = logging.getLogger('median')


@gtin_blueprint.route('<string:ref_pk>', methods=['GET'])
@jwt_required()
def get(ref_pk):
    try:

        filtered_ucd = (
            Ucd.select(Ucd.pk, Ucd.reference, Ucd.ucd)
            .join(Product, on=Product.reference == Ucd.reference)
            .where(Product.pk == ref_pk))

        logger.debug('Lines : %s.' % len(filtered_ucd))

        return {'data': [{
            'ucd': s.ucd,
            'pk': s.pk,
            'reference': s.reference
        } for s in filtered_ucd]}, HTTP_200_OK

    except Exception as error:
        logger.error('Get Ucd raised an exception: ', error.args)
        return {'message': error.args}, HTTP_500_INTERNAL_SERVER_ERROR
