from flask import Blueprint, jsonify, request  # NOQA F401
from marshmallow import fields  # NOQA F401
from marshmallow_enum import EnumField  # NOQA F401
from webargs.fields import DelimitedList

from hobbit_core.utils import use_kwargs
from hobbit_core.pagination import PageParams
from hobbit_core.db import transaction

from app import schemas
from app.services import {{ metadata | map('regex_replace', '^(.*)$', '\\1Service') | join(', ') }}
from app.exts import db

bp = Blueprint('{{ module }}', __name__)


{% for model_name, Model in metadata.items() -%}
@bp.route('/{{ Model.plural }}{{ tail_slash }}', methods=['GET'])
@use_kwargs(PageParams)
def list_{{ Model.plural }}(page, page_size, order_by):
    page_ret = {{ model_name }}Service.list(page, page_size, order_by)
    return jsonify(schemas.paged_{{ Model.singular }}_schemas.dump(page_ret))


@bp.route('/{{ Model.plural }}{{ tail_slash }}', methods=['POST'])
@use_kwargs(schemas.{{ Model.singular }}_schema)
@transaction(db.session)
def create_{{ Model.singular }}(**kwargs):
    instance = {{ model_name }}Service.create(**kwargs)
    return jsonify(schemas.{{ Model.singular }}_schema.dump(instance)), 201


@bp.route('/{{ Model.plural }}/<int:pk>{{ tail_slash }}', methods=['GET'])
def retrieve_{{ Model.singular }}(pk):
    instance = {{ model_name }}Service.get_or_404(pk)
    return jsonify(schemas.{{ Model.singular }}_schema.dump(instance))


@bp.route('/{{ Model.plural }}/<int:pk>{{ tail_slash }}', methods=['PUT'])
@use_kwargs(schemas.{{ Model.singular }}_schema)
@transaction(db.session)
def update_{{ Model.singular }}(pk, **kwargs):
    instance = {{ model_name }}Service.update(pk, **kwargs)
    return jsonify(schemas.{{ Model.singular }}_schema.dump(instance))


@bp.route('/{{ Model.plural }}{{ tail_slash }}', methods=['DELETE'])
@use_kwargs({'ids': DelimitedList(fields.Int())})
@transaction(db.session)
def delete_{{ Model.plural }}(ids):
    {{ model_name }}Service.delete(ids)
    return '', 204
{% if not loop.last %}

{% endif %}
{%- endfor %}