const fs = require("fs");
const path = require("path");
const puppeteer = require("puppeteer-core");

const formatDate = (date) => {
  if (!date) return "-";

  return new Date(date).toLocaleDateString("en-GB");
};

const formatDateTime = (date) => {
  if (!date) return "-";

  return new Date(date).toLocaleString("en-GB");
};

const formatWeight = (weight) => {
  return (Number(weight || 0) / 1000).toFixed(2);
};

const generateDispatchWeighmentPDF = async (dispatch) => {

  try {

    // =========================================
    // TEMPLATE
    // =========================================

    let html = fs.readFileSync(
      path.join(
        __dirname,
        "../../templates/dispatchWeighmentTemplate.html",
      ),
      "utf8",
    );

    // =========================================
    // LOGO
    // =========================================

    const logoPath = path.join(
      __dirname,
      "../../uploads/images/logo.png",
    );

    const logoBase64 = fs.readFileSync(
      logoPath,
      "base64",
    );

    const logoUrl = `data:image/png;base64,${logoBase64}`;

    html = html.replace(
      /{{logo_url}}/g,
      logoUrl,
    );

    // =========================================
    // REPLACEMENTS
    // =========================================

    const replacements = {

      // COMPANY

      company_name:
        dispatch.company_name || "-",

      plant_name:
        dispatch.plant_name || "-",

      // BASIC

      ticket_no:
        dispatch.ticket_no || "-",

      shipment_no:
        dispatch.shipment_no || "-",

      sales_order_no:
        dispatch.sales_order_no || "-",

      // CUSTOMER

      customer_name:
        dispatch.customer_name || "-",

      shipping_address:
        dispatch.shipping_address || "-",

      // PRODUCT

      product_name:
        dispatch.product_name || "-",

      movement_type:
        dispatch.movement_type || "-",

      // VEHICLE

      vehicle_no:
        dispatch.vehicle_number || "-",

      vehicle_type:
        dispatch.vehicle_type || "-",

      vehicle_capacity:
        dispatch.vehicle_capacity || "-",

      // DRIVER

      driver_name:
        dispatch.driver_name || "-",

      driver_contact:
        dispatch.driver_contact || "-",

      // TRANSPORT

      lr_number:
        dispatch.lr_number || "-",

      seal_number:
        dispatch.seal_number || "-",

      transport_agency:
        dispatch.transport_agency || "-",

      // WEIGHT

      // gross_weight:
      //    `${Number(dispatch.gross_weight || 0).toLocaleString("en-IN")}`,

      // tare_weight:
      //     `${Number(dispatch.tare_weight || 0).toLocaleString("en-IN")} `,

      // net_weight:
      //    `${Number(dispatch.net_weight || 0).toLocaleString("en-IN")} `,
      
gross_weight: Number(
  (Number(dispatch.gross_weight || 0) * 1000).toFixed(0)
).toLocaleString(),

tare_weight: Number(
  (Number(dispatch.tare_weight || 0) * 1000).toFixed(0)
).toLocaleString(),

net_weight: Number(
  (Number(dispatch.net_weight || 0) * 1000).toFixed(0)
).toLocaleString(),

     dispatch_qty:
  `${Number(dispatch.dispatch_qty || 0).toLocaleString("en-IN")} ${dispatch.uom || ""}`,

      // DATE TIME

      in_datetime:
        formatDateTime(
          dispatch.entry_time ||
          dispatch.in_time
        ),

      out_datetime:
        formatDateTime(
          dispatch.exit_time
        ),

      // REMARKS

      remarks:
        dispatch.remarks || "-",

      // WEIGHED BY

      weighed_by:
        dispatch.weighed_by ||
        dispatch.created_by_name ||
        "-",
    };

    // =========================================
    // REPLACE ALL VARIABLES
    // =========================================

    Object.entries(replacements).forEach(
      ([key, value]) => {

        html = html.replace(
          new RegExp(`{{${key}}}`, "g"),
          value ?? "-",
        );
      },
    );

    // =========================================
    // BROWSER
    // =========================================

    const browser = await puppeteer.launch({

      headless: true,

      executablePath:
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",

      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-dev-shm-usage",
        "--disable-gpu",
      ],
    });

    // =========================================
    // PAGE
    // =========================================

    const page = await browser.newPage();

    await page.setContent(html, {
      waitUntil: "networkidle0",
    });

    // =========================================
    // PDF
    // =========================================

    const pdf = await page.pdf({

      format: "A4",

      printBackground: true,

      margin: {
        top: "10px",
        bottom: "10px",
        left: "10px",
        right: "10px",
      },
    });

    await browser.close();

    return pdf;

  } catch (error) {

    console.log(
      "DISPATCH WEIGHMENT PDF ERROR:",
      error,
    );

    throw error;
  }
};

module.exports = generateDispatchWeighmentPDF;