export class Csv {
  #headers: string[];
  #body: string;
  #rows: string[][] = [[]];
  constructor(headers: string[], body?: string) {
    if (headers != undefined && headers.length == 0) {
      throw Error("Can't have no headers in csv");
    }
    this.#headers = headers ?? [];
    this.#body = body ?? "";
  }
  getRows(): string[][] {
    return this.#rows;
  }
  getHeaders(): string[] {
    return this.#headers;
  }
  setbody(body: string) {
    this.#body = body;
    return this;
  }
  getBody() {
    return this.#body;
  }
  setHeaders(headers: string[]): Csv {
    this.#headers = headers;
    return this;
  }
  makeHeaders(rawCsv: string): Csv {
    let headers: string[] = [];
    let line: string = rawCsv.substring(0, rawCsv.indexOf("\n"));
    line = this.#lint(line);
    headers = line.split(",");
    this.#headers = headers;
    return this;
  }
  makeRows(): Csv {
    if (this.#body.length == 0) {
      throw Error("Can't make an array of an empty body");
    }
    const lines: string[] = this.#body.split("\n");
    if (lines[lines.length - 1] == "") lines.pop();
    this.#rows = [];
    lines.forEach((line) => {
      line = this.#lint(line);
      const row: string[] = line.split(",");
      this.#rows.push(row);
    });
    return this;
  }
  #lint(line: string): string {
    line = line[line.length - 1] == "," ? line.slice(0, line.length - 1) : line;
    line =
      line[line.length - 1] == "\r" ? line.slice(0, line.length - 1) : line;
    line = line[line.length - 1] == "," ? line.slice(0, line.length - 1) : line;

    let replace = false;
    for (let i = 0; i < line.length; i++) {
      if (line[i] == '"') replace = !replace;
      if (replace) {
        if (line[i] == ",") line = this.#replaceAt(line, i, "-");
      }
    }
    line =
      line[line.length - 1] == "\r" ? line.slice(0, line.length - 1) : line;
    return line;
  }
  #replaceAt(word: string, index: number, char: string) {
    const arrayChar: string[] = word.split("");
    arrayChar[index] = char;
    return arrayChar.join("");
  }
  make() {
    return this.#headers.join() + "\n" + this.#body;
  }
}
