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 location as ctl
from ..forms.location import LocationForm
from staff.lib.forms.errors import (
    invalid_json_error,
    form_data_error,
    default_error,
)
from ..permissions.utils import observer_has_perm

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

FORM_NAME = 'location'


@responding_json
@available_for_external
@require_http_methods(['GET', 'POST'])
@observer_has_perm('edit_location')
@use_request_lang
def edit_location(request, login):
    if request.method == 'GET':
        grid = StaffFormGrid(LocationForm, initial=[
            ctl.LocationCtl(login).get_location_initial()
        ])
        return {
            FORM_NAME: grid.as_front_dict(),
        }

    try:
        form_data = json.loads(request.body)[FORM_NAME][0]
    except ValueError:
        logger.exception('Wrong JSON: %s', request.body)
        return invalid_json_error(request.body), 400
    except (KeyError, IndexError):
        logger.exception('Cannot find form data: %s', FORM_NAME)
        return form_data_error(FORM_NAME), 400

    grid = StaffFormGrid(LocationForm, data=[form_data])
    if not grid.is_valid():
        return {'errors': {FORM_NAME: grid.errors()}}

    try:
        ctl.LocationCtl(login).update_location(
            grid.cleaned_data[0],
            request.user,
        )
    except ctl.LocationError:
        return default_error(), 500

    return {'target': {}}
