import logging

from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from median.models import Adresse, Magasin, Product

from median.views import Emplacement
from median.constant import EcoType

available_adresses_blueprint = Blueprint('available_adresses_blueprint', __name__)

logger = logging.getLogger('median')

# TODO: Move to address blueprint


@available_adresses_blueprint.route('', methods=['GET'])
@jwt_required()
def get_all():
    # get args
    args = request.args
    _ref = args['reference']
    _adr = args['origin_adresse']
    _mag = args['magasin']
    _format = args['format']

    _creation = True if args['creation'] == 'true' else False

    try:
        # get format for origin_address
        if _adr != '-':
            _format = Adresse.get_or_none(Adresse.adresse == _padAddressField(_adr))
            _format = _format.format if _format else None
        else:
            _format = _format.replace('__', ' ')

        equipment = Magasin.select(Magasin.eco_type).where(Magasin.mag == _mag).get()

        # get available addresses when format is found

        if equipment.eco_type != EcoType.Externe.value:
            _available_adr = Emplacement.libre(_ref, _mag, _format, _creation)
        else:
            _available_adr = get_external_locations(_mag, _ref)
        logger.info('Lines : %s.' % len(_available_adr))

    except Exception as error:
        logger.error('Exception levée en cherchant les emplacements libres. Variables => '
                     'ref: "%s", magasin: "%s", format: "%s", creation: "%s"' % (_ref, _mag, _format, _creation))
        return {'message': error.args}, 503

    return _available_adr


def get_external_locations(mag, reference):
    product: Product = Product.get(Product.reference == reference)
    addresses = Adresse.select(Adresse.adresse, Adresse.pk).where(Adresse.magasin == mag)

    return [{
        'id': item.pk,
        'adresse': item.adresse,
        'is_pref': item.adresse == product.adr_pref,
    } for item in addresses]


def _padAddressField(adr):
    _adr_items = adr.split('.')

    _o = []
    for a in _adr_items:
        _o.append(a.rjust(3))

    return '.'.join(_o)
