const { isArray } = require("lodash");
const logger = require("../utils/logger");

function createLogEvent(socket, level, message) {
  if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) {
    // console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`);
    socket.emit("log-event", {
      timestamp: new Date(),
      level,
      message
    });

    logger.log("ws-log-event", level, socket.user.email, socket.recordid, {
      wsmessage: message
    });

    if (socket.logEvents && isArray(socket.logEvents)) {
      socket.logEvents.push({
        timestamp: new Date(),
        level,
        message
      });
    }
    // if (level === "ERROR") {
    //   throw new Error(message);
    // }
  }
}

function createJsonEvent(socket, level, message, json) {
  if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy(level)) {
    //console.log(`[WS LOG EVENT] ${level} - ${new Date()} - ${socket.user.email} - ${socket.id} - ${message}`);
    socket.emit("log-event", {
      timestamp: new Date(),
      level,
      message
    });
  }
  logger.log(
    "ws-log-event-json",
    level,
    socket.user.email,
    socket.recordid,
    {
      wsmessage: message,
      json
    },
    true
  );

  if (socket.logEvents && isArray(socket.logEvents)) {
    socket.logEvents.push({
      timestamp: new Date(),
      level,
      message
    });
  }
  // if (level === "ERROR") {
  //   throw new Error(message);
  // }
}

function createXmlEvent(socket, xml, message, isError = false) {
  if (LogLevelHierarchy(socket.log_level) >= LogLevelHierarchy("SILLY")) {
    socket.emit("log-event", {
      timestamp: new Date(),
      level: isError ? "ERROR" : "SILLY",
      message: `${message}: ${xml}`
    });
  }

  logger.log(
    isError ? "ws-log-event-xml-error" : "ws-log-event-xml",
    isError ? "ERROR" : "SILLY",
    socket.user.email,
    socket.recordid,
    {
      wsmessage: message,
      xml
    },
    true
  );

  if (socket.logEvents && isArray(socket.logEvents)) {
    socket.logEvents.push({
      timestamp: new Date(),
      level: isError ? "ERROR" : "SILLY",
      message,
      xml
    });
  }
}

function LogLevelHierarchy(level) {
  switch (level) {
    case "XML":
      return 5;
    case "SILLY":
      return 5;
    case "DEBUG":
      return 4;
    case "INFO":
      return 3;
    case "WARN":
      return 2;
    case "ERROR":
      return 1;
    default:
      return 3;
  }
}

exports.createLogEvent = createLogEvent;
exports.createXmlEvent = createXmlEvent;
exports.createJsonEvent = createJsonEvent;
