import { getDatetime } from "taehui-ts/date";

import { CommentItem } from "src/Comment";
import DB from "src/system/DB";

export const getComments = async (essayID: number) => {
  const comments = await DB.getComments(essayID);
  const data = new Map<number, CommentItem>();
  const commentItems = new Map<number, CommentItem>();

  comments.forEach(({ targetCommentID, commentID, ...comment }) => {
    const commentItem = { commentID, ...comment, comments: [] };
    if (targetCommentID !== -1) {
      data.get(targetCommentID)?.comments?.push(commentItem);
    } else {
      commentItems.set(commentID, commentItem);
    }
    data.set(commentID, commentItem);
  });

  return Array.from(commentItems.values());
};

export const postComment = async (
  targetCommentID: number,
  essayID: number,
  avatarID: string,
  level: number,
  text: string,
) => {
  return (
    1 <= level &&
    text &&
    DB.postComment(targetCommentID, essayID, avatarID, getDatetime(), text)
  );
};

export const doModifyComment = async (
  commentID: number,
  avatarID: string,
  text: string,
  level: number,
) => {
  return text && DB.doModifyComment(commentID, avatarID, text, level);
};

export const wipeComment = async (
  commentID: number,
  avatarID: string,
  level: number,
) => {
  return DB.wipeComment(commentID, avatarID, level);
};

export const getLatestComments = async () => {
  return DB.getLatestComments();
};
