import json

from django.http import HttpRequest, HttpResponse, JsonResponse, HttpResponseForbidden
from django.views.decorators.http import require_GET, require_POST

from staff.lib.xlsx import make_xlsx_file_response

from staff.workspace_management.forms import RoomSharePieForm
from staff.workspace_management.models import BusinessUnit
from staff.workspace_management.usage_report import (
    BCUsageReportPresenter,
    bc_usage_model,
    BUUsageReportPresenter,
    bu_usage_model,
    offices_area,
)
from staff.workspace_management import use_cases, container


@require_GET
def business_units(request: HttpRequest) -> JsonResponse:
    results = list(BusinessUnit.objects.values('id', 'intranet_status', 'name', 'name_en', 'organization_id'))
    return JsonResponse({'results': results})


@require_GET
def usage_report(request: HttpRequest) -> HttpResponse:
    office_id = request.GET.get('office_id')
    areas = offices_area(office_id)
    pages = [
        BCUsageReportPresenter(bc_usage_model(areas)),
        BUUsageReportPresenter(bu_usage_model(areas)),
    ]
    return make_xlsx_file_response(pages, 'usage_report.xlsx')


@require_POST
def new_share_pie(request: HttpRequest) -> HttpResponse:
    if not request.user.has_perm('workspace_management.can_manage_workspace_areas'):
        return HttpResponseForbidden()

    form = RoomSharePieForm(json.loads(request.body))

    if not form.is_valid():
        return JsonResponse(form.errors_as_dict(), status=400)

    use_case = container.build_container()[use_cases.CreateSharePieUsecase]

    use_case.create(use_cases.CreateSharePieRequest(
        room_id=form.cleaned_data['room'].id,
        author_login=request.user.get_profile().login,
        room_area=form.cleaned_data['room_area'],
        shares=[
            use_cases.CreateShare(share_form['business_unit'].id, share_form['share_value'])
            for share_form in form.cleaned_data['shares']
        ],
    ))

    return JsonResponse(data={'share_pie_id': use_case.share_pie_id})
