import fs from "fs";
import path from "path";
import {
  AssesmentData,
  Competency,
  ReportType,
  Personality,
  WayToDevelop,
} from "./types";

require('dotenv').config();

export const getContent = (type: ReportType): string => {
  let basepath = __dirname;
  if (process.env.baseDir) {
    basepath = process.env.baseDir
  }
  const filePath = path.join(basepath, `/templates/${type}.html`);
  try {
    return fs.readFileSync(filePath, "utf8");
  } catch (error) {
    throw new Error("An error ocurred fetching file");
  }
};

export const replaceAssesmentData = (
  _data: AssesmentData[],
  content: string
) => {
  const dict = Object.fromEntries(_data.flatMap((o) => Object.entries(o)));
  const result = content.replace(
    /\[(.*?)\]/g,
    (match, key) => dict[key] ?? match
  );
  return result;
};

export const getAssets = (_type: ReportType) => {
  const header_logo = "templates/header-logo.png";
  const header_footer = "templates/header-footer.png";
  const header_background = "templates/header-background.png";
  const competency_header = "templates/competency-header.png";
  const ways_to_develop_header = "templates/ways-to-develop-header.png";
  const ways_to_develop_header_2 = "templates/ways-to-develop-header-2.png";
  const personality_assesment_header =
    "templates/personality-assesment-header.png";
  const assets: { [key: string]: string }[] = [
    { headerLogo: header_logo },
    { headerFooter: header_footer },
    { headerBackground: header_background },
    { competencyHeader: competency_header },
    { personalityAssesmentHeader: personality_assesment_header },
    { waysToDevelopHeader: ways_to_develop_header },
    { waysToDevelopHeader2: ways_to_develop_header_2 },
  ];
  return assets;
};

const markedIcon =
  "<img width='15px' height='15px' src='templates/marked.png' class='competency-mark'/>";

const getMark = (mark: boolean) => {
  if (mark) {
    return markedIcon;
  }
  return "<img width='15px' height='15px' style='visibility: hidden' />";
};

const getCompetencies = (data: Competency[], type: "strenght" | "weakness") => {
  let result: string = "";

  data.forEach(({ skill, marked, text }) => {
    const svg = path.join(
      __dirname,
      `templates/assets/${skill}.svg`
    );
    const color = type === "strenght" ? "#8FD2B2" : "#C9747E";
    let svgString = fs.readFileSync(svg, "utf8");
    svgString = svgString.replace(/height=".*?"/, 'height="40"');
    svgString = svgString.replace(/width=".*?"/, 'width="40"');
    svgString = svgString.replace(/fill=".*?"/g, `fill="${color}"`);

    result = result.concat(`
      <div class="row" style="margin-bottom: 1rem; width: 90%; padding: 0 3rem;">
        <div class="column competency-data competency-card competency-card-${type}">
          <div class="row" style="height: 100%">
            <div class="column" style="width: 15%; height:80px; padding: 0.5rem">
              ${svgString}
            </div>
            <div class="column" style="width: 65%; height: 100%">
              <div style=" position: relative;
              top: 40%;
              transform: translateY(-40%);"
              <p style="font-size: 16px; height: 100%; text-align: center;">
                ${skill}
              </p>
            </div>
              
            </div>
            <div class="column" style="width: 5%; margin-top: 0.5rem;">
              ${marked}
            </div>
          </div>
        </div> 
        <div class="column">
          <p style="font-size: 9px;letter-spacing: 0.08rem;line-height: 1.2; font-weight:500; text-align:left;">${text}</p>
        </div>
      </div>`);
  });
  return result;
};

export const replaceCompetenciesStrWeak = (
  data: {
    strength: Competency[];
    weakness: Competency[];
  },
  content: string
) => {
  let result = content;

  let strengths: string = getCompetencies(data.strength, "strenght");
  let weakness: string = getCompetencies(data.weakness, "weakness");
  const base = `<div class="competency-section">
    <div style="width: 100%">
      <div class="row" style="margin: 1rem 0 1rem 3rem">
        <div class="column" style="width: 55%">
          <p style="font-size:x-large">Top 3 likely strengths</p>
        </div>
        <div class="column" style="width: 35%">
          <p style="text-align: right">A key behaviour selected by [organization]
            <img
              src="templates/marked.png"
              width="15px"
              height="15px"
            />
          </p>
        </div>
      </div>
      ${strengths}
      <div class="row" style="margin: 1rem 0 1rem 3rem">
        <div class="column" style="width: 55%">
          <p style="font-size:x-large">Lowest 3 likely development areas</p>
        </div>
      </div>
      ${weakness}
    </div>
  </div>`;
  result = result.replace("[competencyResults]", base);

  return result;
};

export const replacePersonality = (data: Personality[], content: string) => {
  let result = content;
  let personality: string = "";
  data.forEach((p, i) => {
    personality = personality.concat(
      `<div class="row" style='${(i === 4 || i === 9 || i === 14) && "margin-top: 20rem"
      }'>
          <div class="column personality-data personality-card">
            <div class="row" style="height: 90px">
              <div class="column" style="width: 15%">
                <img class="personality-image" src='templates/assets/${p.skill
      }.svg' alt="${p.skill}-image"/>
              </div>
              <div class="column" style="width: 40%">
                <p style="text-align:center; font-size: 16px; word-wrap: break-word; box-sizing: border-box; padding: 0.2rem;">${p.skill
      }</p>
              </div>
              <div class="column" style="width: 5%; margin-right: 4px;">
                ${getMark(p.marked)}
              </div>
              <div class="column" style="width: 37.5%">
                <p class="personality-result" style="text-align:right; float:right">${p.result
      }</p>
              </div>
            </div>
            <div class="row">
              <div class="progress-bar-container">
                <span class="progress-bar" style="width: ${p.barValue}%"></span>
              </div>
            </div>
          </div>
          <div class="column personality-data personality-meaning" style="width: 40%">
            <h3>What this means?</h3>
            ${p.text}
          </div>
        </div>
        `
    );
  });

  const base = `<div class="personality-section">${personality}</div>`;
  result = result.replace("[personalityResults]", base);
  return result;
};

export const replaceWaysToDevelop = (
  _data: WayToDevelop[],
  position: number,
  content: string
) => {
  let result = content;
  let waysToDevelop: string = "";

  for (let i = 0; i < _data.length; i += 2) {
    const card = (wtd: WayToDevelop) => {
      const svg = path.join(
        __dirname,
        `templates/assets/${wtd.skill}.svg`
      );
      let svgString = fs.readFileSync(svg, "utf8");
      svgString = svgString.replace(/height=".*?"/, 'height="50"');
      svgString = svgString.replace(/width=".*?"/, 'width="50"');
      svgString = svgString.replace(/fill=".*?"/g, `fill="#C9747E"`);
      return `
      <div class="row">
        <div class="column" style="width: 100%">
          <div class="competency-data ways-to-develop-card">
            <div class="row" style="height: 100px">
              <div class="column" style="width: 20%; padding: 0.5rem">
                ${svgString}
              </div>
              <div class="column" style="width: 70%; height: 100%">
                <p style="font-size: large; margin-top: 30px; margin-left:0.5rem; font-weight:bold;">${wtd.skill
        }</p>
              </div>
              <div class="column" style="width: 5%; margin-top: 0.5rem;">
                ${getMark(wtd.marked)}
              </div>
            </div>
          </div>
          <div class="row" style="width: 75%; margin-top: 1.5rem;">
            <div class="column" style="width: 100%">
              <div class="row" style="margin-top: 1.5rem">
                <div class="column" style="width:10%">
                  <img width="25px" height="25px" src='templates/checkMark.png' alt="way-to-develop-mark"/>
                </div>
                <div class="column" style="width:85%">
                  <p class="way-to-develop-text">${wtd.texts[0]}</p>
                </div>
              </div>
              <div class="row" style="margin-top: 1.5rem">
                <div class="column" style="width:10%">
                  <img width="25px" height="25px" src='templates/checkMark.png' alt="way-to-develop-mark"/>
                </div>
                <div class="column" style="width:85%">
                  <p class="way-to-develop-text">${wtd.texts[1]}</p>
                </div>
              </div>
              <div class="row" style="margin-top: 1.5rem">
                <div class="column" style="width:10%">
                  <img width="25px" height="25px" src='templates/checkMark.png' alt="way-to-develop-mark"/>
                </div>
                <div class="column" style="width:85%">
                  <p class="way-to-develop-text">${wtd.texts[2]}</p>
                </div>
              </div>
            </div>
          </div>
        </div> 
      </div>
    `;
    };

    let height: number = 750;
    if (i > 1) {
      height = 800;
    }
    waysToDevelop = waysToDevelop.concat(`
      <div style="padding: 0 3rem; margin-top:3rem">
        <div class="row" style="height:${height}px;">
          <div class="column" style="width: 45%">
            ${card(_data[i])}  
          </div>
          <div class="column" style="width: 45%; margin-left: 5%">
            ${card(_data[i + 1])}  
          </div>
        </div>
      </div>  
    `);
  }

  const base = `
    <div class="ways-to-develop-section" style="top:${position}px">
      <div style="position: relative">
        <img
          class="ways-to-develop-header"
          src="templates/ways-to-develop-header.png"
          alt="ways-to-develop-header"
        />
        <div class="ways-to-develop-header ways-to-develop-header-text">
          <p class="title">WAYS TO DEVELOP</p>
          <p>
            Below are tips on how to improve and develop in the areas that are
            less likely to come naturally to you. It’s very rare for someone’s
            personality to change radically; however, by being aware of and
            working on your behaviour, you can improve your confidence and
            performance at work.
          </p>
          <p>
            We suggest you build the tips you find useful into your
            development plan.
          </p>
        </div>
      </div>
      <div class="row" style="width: 100%; margin-top:1rem;">
        <p style="text-align: right; padding-right: 2rem;">A key behaviour selected by [organization]
          <img
            src="templates/marked.png"
            width="15px"
            height="15px"            
          />
        </p>
      </div>
       ${waysToDevelop}
    </div>`;

  result = result.replace("[waysToDevelop]", base);
  return result;
};

export const replacePracticalTips = (content: string, position: number) => {
  let result = content;

  const Card = (title: string, subtitle: string) => `<div class="row">
    <div class="column practical-tips-card">
      <div class="row">
        <p>${title}</p>
      </div>
      <div class="row">
        <p>${subtitle}</p>
      </div>
    </div>
  </div>`;

  const base = `<div class="practical-tips-section" style="top:${position}px">
      <div style="position: relative">
        <img
          class="practical-tips-header"
          src="templates/practical-tips-header.png"
          alt="practical-tips-header"
        />
        <div class="practical-tips-header-text">
          <p>PRACTICAL TIPS FOR YOUR PROFESSIONAL DEVELOPMENT</p>
          <p>
            Below you will find some tips on how to improve your performance within the workplace. Make use of these as well as the more targeted activities on the next page to put together your personalised, achievable development plan. 
          </p>
        </div>
      </div>
      <div class="practical-tips-wrapper">
        <div class="row">
          <div class="column">
            ${Card(
    "Talk to your manager",
    "If you ask managers what contributed most to their professional development, they will almost always cite significant professional challenges. We learn the most when challenging circumstances force us to adopt new attitudes. In these situations, we are taken out of our “comfort zone” into uncharted territory."
  )}  
          </div>
          <div class="column">
          ${Card(
    "Consider your drivers",
    "We are all diverse and unique, so developing your self-awareness involves gaining a deeper understanding of your personality traits, personal values, habits, and the drivers of your behaviours. This is a critical first step to help you understand the steps needed to change or develop a specific behaviour."
  )}  
          </div>
        </div>
        <div class="row">
          <div class="column">
          ${Card(
    "Maximise your training",
    "Find out what types of training opportunities, resources or funding for external courses are available within your company. Discuss your learning goals with your manager and focus on joining training opportunities that target the skill or behaviour you want to develop. Use this as a chance to learn this new behaviour."
  )}  
          </div>
          <div class="column">
          ${Card(
    "Create an action plan",
    "Use the suggestions in this report to help you change your behaviours through targeted activities that take your learning style into account. Put it into practice on a daily basis. Keep in mind that the aim is to set realistic and measurable goals. It is more effective to progress in small steps rather than pursuing an unachievable objective."
  )}  
          </div>
        </div>
        <div class="row">
          <div class="column">
          ${Card(
    "Know when to ask for help",
    "Asking for help the right way can encourage continuous professional development, and should not be seen as a weakness. If you have difficulties developing your action plan, seek help: the advice and assistance of a friend, colleague, or mentor whose experience you can learn from may prove precious."
  )}  
          </div>
          <div class="column">
          ${Card(
    "Embrace feedback",
    "Gather honest feedback from your manager and colleagues about how you are applying your new learning and use this to guide your next steps. While putting your action plan into practice, you should keep an open mind about the feedback. This is the only way to keep track of the change in your behaviour, and ensure that it has the desired effect."
  )}  
          </div>
        </div>
      </div>
    </div>`;
  result = result.replace("[practicalTips]", base);
  return result;
};

export const replaceYourIndividualDevPlan = (
  content: string,
  position: number
) => {
  let result = content;

  const base = `
    <div class="individual-plan-section" style="top:${position}px">
      <div style="position: relative">
        <img
          class="individual-plan-header"
          src="templates/individual-plan-header.png"
          alt="individual-plan-section-header"
        />
        <div class="individual-plan-header-text">
          <p class="title">YOUR INDIVIDUAL DEVELOPMENT PLAN</p>
        </div>
      </div>
      <div class="individual-plan-section-wrapper">
        <div class="row ip-row">
          <div class="column ip-column ip-column-first">
            <p class="ip-column-header">Commitments</p>
          </div>
          <div class="column ip-column">
            <p class="ip-column-header">Your plan</p>
          </div>
        </div>
        <div class="row" style="height: 200px; margin-top:1rem;">
          <div class="column ip-column ip-column-first">
            <p class="ip-column-header">1-3 Commitments</p>
          </div>
          <div class="column ip-column">
            <p class="ip-column-text">I'm going to commit to...</p>
          </div>
        </div>
        <div class="row" style="height: 200px; margin-top:1rem;">
          <div class="column ip-column ip-column-first">
            <p class="ip-column-header">Your why</p>
          </div>
          <div class="column ip-column">
            <p class="ip-column-text">This is important to me because…</p>
          </div>
        </div>
        <div class="row" style="height: 200px; margin-top:1rem">
          <div class="column ip-column ip-column-first">
            <p class="ip-column-header">Timescale </p>
          </div>
          <div class="column ip-column">
            <p class="ip-column-text">I’ll experiment with this for…</p>
          </div>
        </div>
      </div>
    </div>`;
  result = result.replace("[individualPlan]", base);
  return result;
};

export const replaceFooter = (content: string, position: number) => {
  let result = content;

  const base = `
    <div class="page-footer-section" style="top:${position}px">
      <div style="position: relative">
        <img
          class="page-footer-header"
          src="templates/page-footer-header.png"
          alt="page-footer-header"
        />
        <div class="page-footer-header-text">
          <p>THE SCIENCE BEHIND THE ASSESSMENT</p>
          <div>
            <p>Our personality assessment is used across 90 different countries by some of the most respected brands to help them make more ethical, data-driven, informed and consistent decisions, reducing bias and discrimination. Assessments are used by employees to power objective personalised guidance.</p>
            <p>Last year our assessments were completed by over 12 million people.</p>
          </div>
        </div>
      </div>
      <div class="row page-footer-section-wrapper">
        <div class="column page-footer-text">
          <p>Thrive administers the personality assessment which is powered by Aon and their team of 600 psychologists, built over the last 30+ years.</p>
          <p>Your responses to the questionnaire are compared with a very large sample of the population. The assessments are maintained and designed to reduce bias.</p>
          <p>The personality assessment are based on the Five Factor Model.</p>
        </div>
        <div class="column" style="margin-left:4rem">
          <img height="250px" src="templates/footer-image.png"
        </div>
        <img src="templates/header-logo.png" class="footer-logo"/>
      </div>
      
    </div>`;
  result = result.replace("[pageFooter]", base);
  return result;
};
