import { Injectable } from '@nestjs/common';
import { WhiteboardDrawDto } from './dto/whiteboard-draw.dto';

export interface DrawingData extends WhiteboardDrawDto {
  timestamp: number;
  id: string;
}

@Injectable()
export class WhiteboardService {
  // In-Memory Storage für Whiteboard-Daten (später kann man das in eine DB auslagern)
  private whiteboards: Map<string, DrawingData[]> = new Map();
  private activeUsers: Map<string, Set<string>> = new Map();

  addDrawing(whiteboardId: string, drawing: WhiteboardDrawDto): DrawingData {
    const drawingData: DrawingData = {
      ...drawing,
      timestamp: Date.now(),
      id: `${Date.now()}-${Math.random()}`,
    };

    if (!this.whiteboards.has(whiteboardId)) {
      this.whiteboards.set(whiteboardId, []);
    }

    this.whiteboards.get(whiteboardId)!.push(drawingData);
    return drawingData;
  }

  clearWhiteboard(whiteboardId: string): void {
    this.whiteboards.set(whiteboardId, []);
  }

  getWhiteboardData(whiteboardId: string): DrawingData[] {
    return this.whiteboards.get(whiteboardId) || [];
  }

  joinWhiteboard(whiteboardId: string, userId: string): void {
    if (!this.activeUsers.has(whiteboardId)) {
      this.activeUsers.set(whiteboardId, new Set());
    }
    this.activeUsers.get(whiteboardId)!.add(userId);
  }

  leaveWhiteboard(whiteboardId: string, userId: string): void {
    const users = this.activeUsers.get(whiteboardId);
    if (users) {
      users.delete(userId);
      if (users.size === 0) {
        this.activeUsers.delete(whiteboardId);
      }
    }
  }

  getActiveUsers(whiteboardId: string): string[] {
    return Array.from(this.activeUsers.get(whiteboardId) || []);
  }

  getActiveUserCount(whiteboardId: string): number {
    return this.activeUsers.get(whiteboardId)?.size || 0;
  }
}
