import { Server as HTTPServer } from 'http'
import { Namespace, Server as SocketServer, Socket } from 'socket.io'
import { isIdValid } from '@server/helpers/custom-validators/misc.js'
import { Debounce } from '@server/helpers/debounce.js'
import { MVideo, MVideoImmutable } from '@server/types/models/index.js'
import { MRunner } from '@server/types/models/runners/index.js'
import { UserNotificationModelForApi } from '@server/types/models/user/index.js'
import { LiveVideoEventPayload, LiveVideoEventType } from '@peertube/peertube-models'
import { logger } from '../helpers/logger.js'
import { authenticateRunnerSocket, authenticateSocket } from '../middlewares/index.js'
import { isDevInstance } from '@peertube/peertube-node-utils'
import { LiveChatStore } from './live/live-chat-store.js'

class PeerTubeSocket {
  private static instance: PeerTubeSocket

  private userNotificationSockets: { [userId: number]: Socket[] } = {}
  private liveVideosNamespace: Namespace
  private liveChatNamespace: Namespace
  private readonly runnerSockets = new Set<Socket>()
  private readonly liveChatStore = new LiveChatStore()

  private constructor () {}

  init (server: HTTPServer) {
    const io = new SocketServer(server, {
      cors: isDevInstance()
        ? { origin: 'http://localhost:5173', methods: [ 'GET', 'POST' ] }
        : undefined
    })

    io.of('/user-notifications')
      .use(authenticateSocket)
      .on('connection', socket => {
        const userId = socket.handshake.auth.user.id

        logger.debug('User %d connected to the notification system.', userId)

        if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []

        this.userNotificationSockets[userId].push(socket)

        socket.on('disconnect', () => {
          logger.debug('User %d disconnected from SocketIO notifications.', userId)

          this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
        })
      })

    this.liveVideosNamespace = io.of('/live-videos')
      .on('connection', socket => {
        socket.on('subscribe', params => {
          const videoId = params.videoId + ''
          if (!isIdValid(videoId)) return

          void socket.join(videoId)
        })

        socket.on('unsubscribe', params => {
          const videoId = params.videoId + ''
          if (!isIdValid(videoId)) return

          void socket.leave(videoId)
        })
      })

    this.liveChatNamespace = io.of('/live-chat')
      .on('connection', socket => {
        socket.on('join-room', payload => {
          const streamKey = sanitizeStreamKey(payload?.streamKey)
          const username = sanitizeOptionalUsername(payload?.username)

          if (!streamKey) {
            socket.emit('chat-error', { message: 'Invalid stream key.' })
            return
          }

          this.leaveLiveChatRoom(socket)

          const room = this.liveChatStore.joinRoom(streamKey, socket.id)
          ;(socket.data as any).liveChatStreamKey = streamKey
          ;(socket.data as any).liveChatUsername = username

          void socket.join(streamKey)

          socket.emit('recent-messages', {
            streamKey,
            messages: room.messages
          })

          this.emitLiveChatPresence(streamKey)
        })

        socket.on('leave-room', () => {
          this.leaveLiveChatRoom(socket)
        })

        socket.on('send-message', payload => {
          const streamKey = (socket.data as any).liveChatStreamKey as string | undefined
          const username = (socket.data as any).liveChatUsername as string | undefined
          const text = sanitizeMessage(payload?.text)

          if (!streamKey || !username) {
            socket.emit('chat-error', { message: 'Join a room before sending messages.' })
            return
          }

          if (!text) {
            socket.emit('chat-error', { message: 'Message cannot be empty.' })
            return
          }

          const lastSentAt = ((socket.data as any).liveChatLastSentAt as number | undefined) || 0
          if (Date.now() - lastSentAt < 1000) {
            socket.emit('chat-error', { message: 'You are sending messages too quickly.' })
            return
          }

          ;(socket.data as any).liveChatLastSentAt = Date.now()

          const message = this.liveChatStore.addMessage(streamKey, username, text)
          this.liveChatNamespace.in(streamKey).emit('new-message', {
            streamKey,
            message
          })
        })

        socket.on('disconnect', () => {
          this.leaveLiveChatRoom(socket)
        })
      })

    io.of('/runners')
      .use(authenticateRunnerSocket)
      .on('connection', socket => {
        const runner: MRunner = socket.handshake.auth.runner

        logger.debug(`New runner "${runner.name}" connected to the notification system.`)

        this.runnerSockets.add(socket)

        socket.on('disconnect', () => {
          logger.debug(`Runner "${runner.name}" disconnected from the notification system.`)

          this.runnerSockets.delete(socket)
        })
      })
  }

  sendNotification (userId: number, notification: UserNotificationModelForApi) {
    const sockets = this.userNotificationSockets[userId]
    if (!sockets) return

    logger.debug('Sending user notification to user %d.', userId)

    const notificationMessage = notification.toFormattedJSON()
    for (const socket of sockets) {
      socket.emit('new-notification', notificationMessage)
    }
  }

  // ---------------------------------------------------------------------------

  sendVideoLiveNewState (video: MVideo) {
    const data: LiveVideoEventPayload = { state: video.state }
    const type: LiveVideoEventType = 'state-change'

    logger.debug('Sending video live new state notification of %s.', video.url, { state: video.state })

    this.liveVideosNamespace
      .in(video.id + '')
      .emit(type, data)
  }

  sendVideoViewsUpdate (video: MVideoImmutable, numViewers: number) {
    const data: LiveVideoEventPayload = { viewers: numViewers }
    const type: LiveVideoEventType = 'views-change'

    logger.debug('Sending video live views update notification of %s.', video.url, { viewers: numViewers })

    this.liveVideosNamespace
      .in(video.id + '')
      .emit(type, data)
  }

  sendVideoForceEnd (video: MVideo) {
    const type: LiveVideoEventType = 'force-end'

    logger.debug('Sending video live "force end" notification of %s.', video.url)

    this.liveVideosNamespace
      .in(video.id + '')
      .emit(type)
  }

  async closeLiveChatRoom (streamKey: string, reason: 'live-ended' | 'rescheduled' | 'deleted' = 'live-ended') {
    if (!streamKey) return

    const sockets = await this.liveChatNamespace.in(streamKey).fetchSockets()

    for (const socket of sockets) {
      this.liveChatStore.leaveRoom(streamKey, socket.id)
      void socket.leave(streamKey)

      if ((socket.data as any).liveChatStreamKey === streamKey) {
        delete (socket.data as any).liveChatStreamKey
        delete (socket.data as any).liveChatUsername
        delete (socket.data as any).liveChatLastSentAt
      }

      socket.emit('room-closed', { streamKey, reason })
    }

    this.liveChatStore.deleteRoom(streamKey)
    this.emitLiveChatPresence(streamKey)
  }

  // ---------------------------------------------------------------------------

  @Debounce({ timeoutMS: 1000 })
  sendAvailableJobsPingToRunners () {
    logger.debug(`Sending available-jobs notification to ${this.runnerSockets.size} runner sockets`)

    for (const runners of this.runnerSockets) {
      runners.emit('available-jobs')
    }
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }

  private emitLiveChatPresence (streamKey: string) {
    this.liveChatNamespace.in(streamKey).emit('presence-update', {
      streamKey,
      count: this.liveChatStore.getPresenceCount(streamKey)
    })
  }

  private leaveLiveChatRoom (socket: Socket) {
    const streamKey = (socket.data as any).liveChatStreamKey as string | undefined
    if (!streamKey) return

    this.liveChatStore.leaveRoom(streamKey, socket.id)
    void socket.leave(streamKey)

    delete (socket.data as any).liveChatStreamKey
    delete (socket.data as any).liveChatUsername
    delete (socket.data as any).liveChatLastSentAt

    this.emitLiveChatPresence(streamKey)
  }
}

function sanitizeStreamKey (streamKey: unknown) {
  if (typeof streamKey !== 'string') return undefined
  if (!/^[A-Za-z0-9._-]+$/.test(streamKey)) return undefined

  return streamKey
}

function sanitizeUsername (username: unknown) {
  if (typeof username !== 'string') return undefined

  const value = username.trim().replace(/\s+/g, ' ')
  if (value.length < 2 || value.length > 40) return undefined

  return value
}

function sanitizeOptionalUsername (username: unknown) {
  if (username === undefined || username === null || username === '') return undefined

  return sanitizeUsername(username)
}

function sanitizeMessage (text: unknown) {
  if (typeof text !== 'string') return undefined

  const value = text.trim().replace(/\s+/g, ' ')
  if (value.length < 1 || value.length > 500) return undefined

  return value
}


// ---------------------------------------------------------------------------

export {
  PeerTubeSocket
}
