from staff.lib.utils.qs_values import extract_related
from staff.map.models import Room, ROOM_TYPES
from staff.map.edit.objects import ConferenceRoomCtl, RoomCtl
from staff.map.controllers.room_common import update_room_common, create_room_common, delete_room_common
from staff.map.errors import MapApiError, item_does_not_exist_by_id

import logging
logger = logging.getLogger('map.controllers.room')


CONFERENCE_ROOM_FIELDS = (
    'name', 'name_en', 'name_alternative', 'name_exchange', 'order',
    'is_cabin', 'is_avallable_for_reserve', 'floor__office', 'floor', 'coord_x', 'coord_y',
    'geometry', 'iso_label_pos', 'hide_floor_num', 'iso_x', 'iso_y',
    'label_pos', 'marker_board', 'cork_board', 'phone', 'video_conferencing',
    'guest_wifi', 'voice_conferencing', 'projector', 'panel', 'desk', 'seats',
    'capacity', 'additional'
)


class ConferenceRoomError(MapApiError):
    pass


def get_initial(room_id=None):
    if room_id is None:
        return {}

    with item_does_not_exist_by_id(Room)(logger=logger, message_params=[room_id], raise_e=ConferenceRoomError):
        conference_room = (
            Room.objects.values(*CONFERENCE_ROOM_FIELDS)
            .filter(room_type=ROOM_TYPES.CONFERENCE)
            .get(id=room_id, intranet_status=1)
        )
        conference_room.update(extract_related(conference_room, 'floor_'))
        return conference_room


def update_conferenceroom(room_id, data, author):
    with item_does_not_exist_by_id(Room)(logger=logger, message_params=[room_id], raise_e=ConferenceRoomError):
        room = Room.objects.get(id=room_id)

    update_room_common(ConferenceRoomCtl, ConferenceRoomError, room, data, author)


def create_conferenceroom(data, author) -> RoomCtl:
    data['room_type'] = ROOM_TYPES.CONFERENCE
    return create_room_common(ConferenceRoomCtl, ConferenceRoomError, data, author)


def delete_conferenceroom(room_id, author) -> RoomCtl:
    with item_does_not_exist_by_id(Room)(logger=logger, message_params=[room_id], raise_e=ConferenceRoomError):
        room = Room.objects.get(id=room_id, intranet_status=1)
    return delete_room_common(ConferenceRoomCtl, ConferenceRoomError, room, author)
