import json
import logging

from django.http import JsonResponse
from django.shortcuts import get_object_or_404
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.errors import (
    general_error,
    invalid_json_error,
    NO_DATA_PROVIDED,
    sform_general_error,
)
from staff.person.models import Staff

from staff.person_profile.controllers import photos as ctl
from staff.person_profile.permissions.utils import observer_has_perm
from staff.person_profile.views.photos_view import get_photos


logger = logging.getLogger(__name__)


@responding_json
@available_for_external
@require_http_methods(['POST'])
@observer_has_perm('upload_photo')
@use_request_lang
def upload_photo(request, login):
    photo_url = None
    photo_file = request.FILES.get('file')
    if not photo_file:
        try:
            photo_url = json.loads(request.body).get('photo_url')
        except ValueError:
            logger.exception('Wrong JSON: %s', request.body)
            return invalid_json_error(request.body), 400

    if not (photo_file or photo_url):
        return general_error(NO_DATA_PROVIDED), 400

    try:
        target_person = Staff.objects.get(login=login)
        ctl.PhotosCtl(target_person).upload_photo(picture_file=photo_file, picture_url=photo_url)
    except ctl.PhotoError as e:
        logger.info('Error uploading photo', exc_info=True)
        return sform_general_error(e.message), e.status_code

    return {
        'target': {'photos': get_photos(target_person)}
    }


@available_for_external
@require_http_methods(['DELETE'])
@observer_has_perm('delete_all_photos')
@use_request_lang
def delete_all_photos(request, login):
    target_person = get_object_or_404(Staff, login=login)
    ctl.PhotosCtl(target_person).delete_all_photos()
    return JsonResponse(data={})
