from staff.map.models import Device

from staff.map.edit.objects import EquipmentCtl
from staff.lib.utils.qs_values import extract_related

from staff.map.errors import MapApiError, item_does_not_exist_by_id

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


EQUIPMENT_FIELDS = (
    'type',
    'name',
    'name_dns',
    'description',
    'coord_x',
    'coord_y',
    'color',
    'floor',
    'floor__office',
    'angle',
)


class EquipmentError(MapApiError):
    pass


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

    with item_does_not_exist_by_id(Device)(
            logger=logger,
            message_params=[equipment_id],
            raise_e=EquipmentError):
        equipment_item = (
            Device.objects
            .values(*EQUIPMENT_FIELDS)
            .get(id=equipment_id, intranet_status=1)
        )
        equipment_item.update(extract_related(equipment_item, 'floor_'))
        return equipment_item


def update_equipment(device, data, author):
    try:
        EquipmentCtl(device, author).modify(data)
    except Exception:
        logger.exception('Error trying to update equipment with id %s', device.id)
        raise EquipmentError('cannot-update-equipment')


def disable_equipment(device, author):
    try:
        return EquipmentCtl(device, author).disable()
    except Exception:
        logger.exception('Error trying to delete equipment.')
        raise EquipmentError('cannot-delete-equipment')
