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 staff.lib.forms.staff_form_grid import StaffFormGrid

from ..controllers import cars as ctl

from ..forms.car import CarForm
from staff.lib.forms.errors import (
    invalid_json_error,
    default_error,
)
from ..permissions.utils import observer_has_perm
from ..views.cars_view import cars as cars_view

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


FORM_NAME = 'cars'


@responding_json
@available_for_external
@require_http_methods(['GET', 'POST'])
@observer_has_perm('edit_cars')
@use_request_lang
def edit_cars(request, login):
    if request.method == 'GET':
        try:
            return {
                FORM_NAME: (StaffFormGrid(
                    CarForm,
                    initial=ctl.get_cars_initial(login)
                ).as_front_dict())
            }
        except ctl.CarsError:
            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 = StaffFormGrid(CarForm, data=form_data)
    if not grid.is_valid():
        return {'errors': {FORM_NAME: grid.errors()}}
    try:
        ctl.update_cars(login, grid.cleaned_data)
    except ctl.CarsError:
        return default_error(), 500

    return cars_view(request, login)
