import { join } from 'path';
import fs from 'fs';
import { IcyNetUser } from '../../common/types/user';

export class Logger {
  private _stream!: fs.WriteStream;

  constructor(private _path = join(process.cwd(), 'chat.log')) {}

  initialize() {
    this._stream = fs.createWriteStream(this._path, {
      flags: 'a',
      encoding: 'utf-8',
    });
  }

  /**
   * Write a chat message to the log file.
   * @param user Sender
   * @param message Message
   */
  writeChat(user: IcyNetUser, message: string) {
    const date = this._createTimestamp(new Date());
    const userStamp = `${user.display_name}:${user.id}`;
    const fullStamp = `${date} <${userStamp}> ${message}`;
    this._stream.write(`${fullStamp}\n`);
  }

  /**
   * Write a server event to the log file.
   * @param event Event name
   * @param message Event description
   */
  writeEvent(event: string, message: string) {
    const date = this._createTimestamp(new Date());
    this._stream.write(`${date} %EVENT:${event}% ${message}\n`);
  }

  /**
   * Returns timestamp in `YYYY/MM/DD HH:mm:ss` format.
   * @param date Message time
   * @returns Message timestamp
   */
  private _createTimestamp(date: Date): string {
    const az = (n: number) => n.toString().padStart(2, '0');
    const dateStamp = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
      .map(az)
      .join('/');

    const timeStamp = [date.getHours(), date.getMinutes(), date.getSeconds()]
      .map(az)
      .join(':');
    return `[${dateStamp} ${timeStamp}]`;
  }
}
