/**
 * Logs 模块
 * 使用 LogsModule 包裹后,为某个安装流程增加日志处理,并且对外还是返回 Promise 对象
 */

import { Socket } from "socket.io";

let websocket: Map<string, Socket> = new Map()
export function setWebsocketIo (username: string, io: Socket) {
  websocket.set(username, io)
}
export function getWebsocketIo (username: string) {
  return websocket.get(username) as Socket
}

export function sendProjectStatus (platform: 'v1' | 'v2', username: string, status: string) {
  const socket = getWebsocketIo(username)
  const eventData = {
    type: 'Status',
    message: status
  }
  socket.emit(platform, JSON.stringify(eventData))
}

export function sendSocketMessage (username: string, eventName: string, message: string) {
  const socket = getWebsocketIo(username)
  socket.emit(eventName, message)
}

export default class LogUtil {
  // 根据 log 判断用户是否已经执行过
  static async run (username: string, log: string, cb: () => Promise<void>) {
    let socket = getWebsocketIo(username)
    socket.emit('Log', '[progress] [1m[Loading][m ' + log + '中...\n')
    await cb()
    socket.emit('Log', '[progress] [1m[Info][m ' + log + '完成\n')
  }
  static async print(username: string, log: string) {
    let socket = getWebsocketIo(username)
    socket.emit('Log', removeUnreadCharacter(log))
  }
  static async printInfo(username: string, log: string) {
    let socket = getWebsocketIo(username)
    socket.emit('Log', removeUnreadCharacter(`[progress] [[1;34mInfo[m] ${log} \n`))
  }
  static async printError(username: string, log: string) {
    let socket = getWebsocketIo(username)
    socket.emit('Log', removeUnreadCharacter(`[error] [[1;31mError[m] ${log} \n`))
  }
  static async printSuccess(username: string, log: string) {
    let socket = getWebsocketIo(username)
    socket.emit('Log', removeUnreadCharacter(`[progress] [[1;31mSuccess[m] ${log} \n`))
  }
  static async printWarning (username: string, log: string) {

  }
  static clear (username: string) {
    let socket = getWebsocketIo(username)
    socket.emit('ClearLog')
  }
  static printNotification (username: string, notification: string) {
    let socket = getWebsocketIo(username)
    socket.emit('Notification', removeUnreadCharacter(notification))
  }
}