import {
  getAssets,
  getContent,
  replaceAssesmentData,
  replaceCompetenciesStrWeak,
  replaceFooter,
  replacePersonality,
  replacePracticalTips,
  replaceWaysToDevelop,
  replaceYourIndividualDevPlan,
} from "./utils";
import { Promise } from "bluebird";
import { ReportType, RequestData } from "./types";

const pdf = Promise.promisifyAll(require("html-pdf"));

const createPDF = (html: string) => {
  var options = {
    format: "A4",
    base: "file:///" + __dirname + "/",
    localUrlAccess: true, // set this to true to enable local file access
  };
  return new Promise((resolve, reject) => {
    pdf.create(html, options).toBuffer((err: any, buffer: Buffer) => {
      if (err !== null) {
        reject(err);
      } else {
        resolve(buffer);
      }
    });
  });
};

const createReport = async (_data: RequestData, type: ReportType) => {
  let content: string;

  //Get the template corresponding to report
  try {
    content = getContent(type);
    const assets = getAssets(type);
    console.log(_data);

    content = replaceAssesmentData(
      [..._data.params.header, ...assets],
      content
    );
    content = replaceCompetenciesStrWeak(_data.params.competencies, content);
    content = replacePersonality(_data.params.personality, content);

    const averageHeight = 260; //Estimated height for personality card
    let nextPosition = 2125 + averageHeight * _data.params.personality.length;
    if (_data.params.waysToDevelop) {
      content = replaceWaysToDevelop(
        _data.params.waysToDevelop,
        nextPosition,
        content
      );
    }
    const wtdQty = _data.params.waysToDevelop.length;
    nextPosition =
      wtdQty / 2 === 1
        ? 850 * (wtdQty / 2) + nextPosition + 127
        : 1200 * (wtdQty / 2) + nextPosition + 127;
    content = replacePracticalTips(content, nextPosition);
    nextPosition = nextPosition + 1000;
    content = replaceYourIndividualDevPlan(content, nextPosition);
    nextPosition = nextPosition + 1240;
    content = replaceFooter(content, nextPosition);
    const buffer = await createPDF(content);
    return buffer;
  } catch (e) {
    console.error(e);
    throw Error();
  }
};

export { createReport };
