import { exec } from 'child_process';

const nodemailer = require('nodemailer');

exec('iching divine', (error, stdout, stderr) => {

    console.log(`Begin`);

    if (error) {
        console.error(`Error: ${error.message}`);
        return;
    }

    if (stderr) {
        console.error(`Stderr: ${stderr}`);
        return;
    }

    //console.log(`Ergebnis:\n${stdout}`);

    console.log(`Send E-Mail`);

    sendEmail(stdout);

    sleep();
});

// Create Transporter
const transporter = nodemailer.createTransport({
    host: "mailhog.mailhog.svc.cluster.local", // MailHog ClusterIP
    port: 1025,         // Standard-MailHog SMTP-Port
    secure: false       // MailHog needs no encryption
});
  
// Send E-Mail
async function sendEmail(content: string) {
  try {
    const info = await transporter.sendMail({
      from: '"Test Sender" <test@example.com>',
      to: "Christopher.Hase@telekom.com;test@mailhog.local",
      subject: "Horoscope from MailHog",
      text: content,
      //html: "<p> ${content} </p>"
      html: html(content)
    });

    console.log("E-Mail sent: ", info.messageId);
  } catch (error) {
    console.error("Error Sending E-Mail:", error);
  }
}

//Sleep. To avoid issue in pod: Completed -> Terminated -> CrashLoopBackOff 
async function sleep() {
  console.log("Go to sleep: ", new Date().toISOString());

    // sleep 1h (3600000 ms)
    setTimeout(() => {
      sleep(); // recursion after 1h
  }, 3600000);  
}



function html(input: string): string {

    // Zerlege den String in einzelne Zeilen
    const lines = input.split("\n");

    // Bearbeite jede Zeile (z.B. trimme Leerzeichen und füge einen Prefix hinzu)
    //const processedLines = lines.map(line => `> ${line.trim()}`);
    const processedLines = lines.map(line => processLine(line));

    // Füge die Zeilen wieder zu einem String zusammen
    return processedLines.join("\n");
}

//TODO: process every line...
function processLine(input: string): string {

  return input;
}
  