from common.status import HTTP_200_OK
from flask import Blueprint
from flask_jwt_extended import jwt_required
from ressources.acced.block_cause.block_cause_service import get_causes_request, get_ref_by_lock_adresse_request

block_causes_blueprint = Blueprint('block_causes', __name__)


@block_causes_blueprint.route('count', methods=['POST'])
@jwt_required()
def count():
    res = get_causes_request().count()
    return {
        "data": res
    }, HTTP_200_OK


@block_causes_blueprint.route('<string:adr_pk>/references', methods=['POST'])
@jwt_required()
def get_ref_by_lock_adresse(adr_pk):
    req = get_ref_by_lock_adresse_request(adr_pk).objects()

    res = []

    for ref in req:

        reference = next(filter(lambda r: r['reference'] == ref.reference, res), None)

        if reference is None:
            reference = {
                "reference": ref.reference,
                "designation": ref.designation if hasattr(ref, 'designation') else None,
                "count": 0,
                "causes": []
            }
            res.append(reference)

        reference['count'] = reference['count'] + ref.count
        reference['causes'].append({
            'code': ref.cause_code,
            'label': ref.cause_designation,
            "count": ref.count,
        })

    return {
        "list": res
    }, HTTP_200_OK


@block_causes_blueprint.route('all', methods=['POST'])
@jwt_required()
def get():
    causes = get_causes_request().objects()

    res = []
    for cause in causes:
        address = next(filter(lambda c: c['title'] == cause.title, res), None)

        if address is None:
            address = {
                "title": cause.title,
                "subtitle": cause.subtitle if hasattr(cause, 'subtitle') else '',
                "pk": cause.address_pk,
                "causes": []
            }
            res.append(address)

        block_cause = next(filter(lambda c: c['code'] == cause.cause, address['causes']), None)

        if block_cause is None:
            block_cause = {
                'code': cause.cause,
                'label': cause.designation,
                'dates': []
            }
            address['causes'].append(block_cause)

        block_cause['dates'].append({
            'year': cause.year,
            'week': cause.week,
            'nb': cause.nb
        })

    return {
        "list": res
    }, HTTP_200_OK
