import {PentestStatus} from '@shared/models/pentest-status.model';
import {Category} from '@shared/models/category.model';
import {v4 as UUID} from 'uuid';

export class Pentest {
  id?: string;
  projectId?: string;
  category: Category;
  refNumber: string;
  childEntries?: Pentest[];
  status: PentestStatus;
  enabled: boolean;
  findingIds?: Array<string>;
  commentIds?: Array<string>;
  timeSpent?: number;

  constructor(category: Category,
              refNumber: string,
              status: PentestStatus,
              enabled: boolean,
              id?: string,
              projectId?: string,
              findingsIds?: Array<string>,
              commentsIds?: Array<string>,
              timeSpent?: number) {
    this.id = id ? id : UUID();
    this.projectId = projectId ? projectId : '';
    this.category = category;
    this.refNumber = refNumber;
    this.status = status;
    this.enabled = enabled;
    this.findingIds = findingsIds ? findingsIds : [];
    this.commentIds = commentsIds ? commentsIds : [];
    this.timeSpent = timeSpent ? timeSpent : 0;
  }
}

export interface ObjectiveEntry {
  refNumber: string;
  status: string;
  enabled: boolean;
  findings?: number;
  kind?: string;
  childEntries?: ObjectiveEntry[];
  expanded?: boolean;
}

export function isSubObjective(pentest: Pentest): boolean {
  return pentest.refNumber.includes('_');
}

export function getObjectiveNumberObjective(pentest: Pentest): string {
  return pentest.refNumber.split('_')[0];
}

export function transformPentestToRequestBody(pentest: Pentest): Pentest {
  const transformedPentest = {
    ...pentest,
    projectId: pentest.projectId,
    category: typeof pentest.category === 'number' ? Category[pentest.category] : pentest.category,
    refNumber: pentest.refNumber,
    status: pentest.status,
    enabled: pentest.enabled,
    findingIds: pentest.findingIds ? pentest.findingIds : [],
    commentIds: pentest.commentIds ? pentest.commentIds : [],
    /* Remove Table Entry Object Properties */
    childEntries: undefined,
    kind: undefined,
    findings: undefined,
    expanded: undefined,
  } as unknown as Pentest;
  return transformedPentest;
}

export function transformPentestsToObjectiveEntries(pentests: Pentest[]): ObjectiveEntry[] {
  const objectiveEntries: ObjectiveEntry[] = [];
  pentests.forEach((value: Pentest) => {
    objectiveEntries.push({
      id: value.id,
      refNumber: value.refNumber,
      status: value.status,
      enabled: value.enabled,
      findingIds: value.findingIds,
      commentIds: value.commentIds,
      kind: value.childEntries ? 'dir' : 'cell',
      childEntries: value.childEntries ? value.childEntries : null,
      expanded: !!value.childEntries
    } as ObjectiveEntry);
  });
  return objectiveEntries;
}
