import json

from django.views.decorators.http import require_http_methods

from staff.lib.decorators import (
    responding_json,
    use_request_lang,
    available_for_external,
)

from ..controllers import bicycles as ctl

from ..forms.bicycle import BicycleGrid, BicycleForm
from staff.lib.forms.errors import (
    invalid_json_error,
    default_error,
)
from ..permissions.utils import observer_has_perm
from ..views.bicycles_view import bicycles as bicycles_view

import logging
logger = logging.getLogger('person_profile.edit_views.edit_bicycles_view')


FORM_NAME = 'bicycles'


@responding_json
@available_for_external
@require_http_methods(['GET', 'POST'])
@observer_has_perm('edit_bicycles')
@use_request_lang
def edit_bicycles(request, login):
    if request.method == 'GET':
        try:
            return {
                FORM_NAME: (BicycleGrid(
                    BicycleForm,
                    initial=ctl.get_bicycles_initial(login),
                    owner_login=login,
                ).as_front_dict())
            }
        except ctl.BicyclesError:
            return default_error(), 500

    try:
        form_data = json.loads(request.body).get(FORM_NAME, [])
    except ValueError:
        logger.exception('Wrong JSON: %s', request.body)
        return invalid_json_error(request.body), 400

    grid = BicycleGrid(BicycleForm, data=form_data, owner_login=login)
    if not grid.is_valid():
        return {'errors': {FORM_NAME: grid.errors()}}
    try:
        ctl.update_bicycles(login, grid.cleaned_data)
    except ctl.BicyclesError:
        return default_error(), 500

    return bicycles_view(request, login)
