"""WebSocket consumer: one connection per app device.

Client -> server: {"type": "ping"}          (keep-alive + heartbeat)
Server -> client: {"type": "hello"}         (connected)
                  {"type": "pong"}
                  {"type": "webrtc.session", ...session}
                  {"type": "webrtc.candidate", ...candidate}
                  {"type": "pairing.updated", "device_id": ...}
"""
import logging

from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from django.utils import timezone

from .realtime import device_group, notify_devices

logger = logging.getLogger(__name__)

CLOSE_UNAUTHORIZED = 4001
CLOSE_FORBIDDEN = 4003


@database_sync_to_async
def _owned_device(user, device_id):
    from .models import SecurityDevice

    return SecurityDevice.objects.filter(device_id=device_id, user=user).first()


@database_sync_to_async
def _set_presence(device_id, online):
    """Update online flag; return ids of paired devices to tell."""
    from .models import SecurityDevice

    device = SecurityDevice.objects.filter(device_id=device_id).first()
    if device is None:
        return []
    changed = device.is_online != online
    device.is_online = online
    device.last_seen = timezone.now()
    device.save(update_fields=['is_online', 'last_seen'])
    if not changed:
        return []
    return list(device.paired_devices.values_list('device_id', flat=True))


class DeviceConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        user = self.scope.get('user')
        self.device_id = self.scope['url_route']['kwargs']['device_id']
        self.group = None

        # Accept before closing so the client receives the close code
        # (4001 -> refresh token and retry; 4003 -> wrong device).
        if user is None or not user.is_authenticated:
            await self.accept()
            await self.close(code=CLOSE_UNAUTHORIZED)
            return
        if await _owned_device(user, self.device_id) is None:
            await self.accept()
            await self.close(code=CLOSE_FORBIDDEN)
            return

        self.group = device_group(self.device_id)
        await self.channel_layer.group_add(self.group, self.channel_name)
        await self.accept()
        await self.send_json({'type': 'hello', 'device_id': self.device_id})
        await self._presence(True)

    async def disconnect(self, code):
        if self.group:
            await self.channel_layer.group_discard(self.group, self.channel_name)
            await self._presence(False)

    async def receive_json(self, content, **kwargs):
        if content.get('type') == 'ping':
            await self._presence(True)
            await self.send_json({'type': 'pong'})

    async def device_event(self, event):
        # Event name last so a payload field called "type" can't override it.
        await self.send_json({**event.get('payload', {}), 'type': event['event']})

    async def _presence(self, online):
        try:
            paired = await _set_presence(self.device_id, online)
        except Exception:
            logger.warning('presence update failed device=%s', self.device_id, exc_info=True)
            return
        if paired:
            await database_sync_to_async(notify_devices)(
                paired, 'pairing.updated', {'device_id': self.device_id, 'is_online': online}
            )
