from django.conf import settings
from django.shortcuts import render
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import ensure_csrf_cookie

from staff.map.models import Floor
from staff.map.permissions import get_user_permissions

from staff.lib.decorators import responding_json

from staff.whistlah.utils import get_last_activity

from .forms.forms import FloorMapForm
from .tasks import TileCutter

import logging

logger = logging.getLogger(__name__)


def choose_default_floor_and_office(requested_by):
    la = get_last_activity([requested_by.login])[requested_by.login]
    table = requested_by.table

    def floor_and_office():
        if not table:
            return None, None
        return table.floor, table.floor.office

    if la and la.get('office_id'):
        office_id = la['office_id']
        if office_id == settings.REDROSE_OFFICE_ID:  # если последняя активность из КР
            if table and table.floor.office_id in settings.REDROSE_OFFICES:  # сотрудник работает в КР
                return floor_and_office()
            else:  # Сотрудник нигде не прописан, либо прописан вне КР
                return None, None
        else:  # если последняя активность не КР
            if table and table.floor.office_id == office_id:  # сотрудник активен в офисе где прописан
                return floor_and_office()
            else:  # Сотрудник активен в чужом офисе
                try:
                    floor = (
                        Floor.objects.select_related('office')
                        .filter(office_id=office_id)
                        .exclude(num=None)
                        .exclude(num__lte=0)
                        .order_by('num')
                    )[0]
                except IndexError:
                    return floor_and_office()
                return floor, floor.office

    elif table:
        return floor_and_office()

    return None, None


@permission_required('map.can_upload_floor_map')
def upload_image(request):
    if request.method == 'POST':
        confirm_email = request.user.staff.email

        try:
            form = FloorMapForm(request.POST, request.FILES)
            if form.is_valid():
                obj = form.save()

                map_is_for = '{office}, {floor}'.format(
                    office=form.instance.floor.office,
                    floor=form.instance.floor,
                )

                TileCutter.apply_async(
                    countdown=20,
                    kwargs={
                        'map_id': obj.id,
                        'confirm_email': confirm_email,
                        'map_is_for': map_is_for,
                    },
                )

                return HttpResponseRedirect(
                    reverse('map:map-upload-complete', args=[obj.file_name])
                )
        except Exception:
            logger.exception('Can\'t upload map image')
            return HttpResponse('Не удалось загрузить карту.', status=500)

    else:
        form = FloorMapForm()
    return render(request, 'map/upload_image.html', {'form': form})


@permission_required('map.can_upload_floor_map')
def upload_image_complete(request, file_name):
    return render(
        request,
        'map/upload_image_complete.html',
        {'file_name': file_name}
    )


@ensure_csrf_cookie
@responding_json
def meta(request):
    requested_by = request.user.get_profile()
    floor, office = choose_default_floor_and_office(requested_by=requested_by)
    return {
        'floor_id': floor and floor.id,
        'office_code': office and office.code,
        'office_id': office and office.id,
        'permissions': get_user_permissions(requested_by.user),
        'show_security_devices': request.user.has_perm('django_intranet_stuff.can_view_security_devices')
    }
