const {
  formatDateTime,
  padLeft,
  padRight,
} = require("../../src/utils/ecservice-utils");

function buildBillTemplate({
  order,
  lineWidth,
  descWidth,
  priceWidth,
  totalWidth,
  labelWidth,
  valueWidth,
  settings,
}) {
  const items = Array.isArray(order.items) ? order.items : [];
  const specials = Array.isArray(order.specials) ? order.specials : [];
  const sortingArray = items.concat(specials).sort((left, right) =>
    left.sort > right.sort ? 1 : right.sort > left.sort ? -1 : 0,
  );

  let header = "\x1B\x4D\x00";
  let output = "\x1B\x4D\x00";
  let footer = "\x1B\x4D\x00";

  if (settings.print_header1) header += `${settings.print_header1}\n`;
  if (settings.print_header2) header += `${settings.print_header2}\n`;
  if (settings.print_header3) header += `${settings.print_header3}\n`;
  if (settings.print_header4) header += `${settings.print_header4}\n`;
  if (settings.print_header5) header += `${settings.print_header5}\n`;
  if (settings.print_directly_bill_fiscal == "false") {
    header += "DOCUMENTO NON FISCALE\n";
  }

  output += "\n";
  output +=
    padRight("DESCRIZIONE", descWidth) +
    padLeft("PREZZO", priceWidth) +
    padLeft("TOT", totalWidth) +
    "\n";
  output += "-".repeat(lineWidth) + "\n";

  sortingArray.forEach((orderItem) => {
    const qty = parseFloat(orderItem.quantity) || 1;
    const name =
      orderItem.product?.name ||
      orderItem.name ||
      orderItem.product_name ||
      "ND";
    const price = parseFloat(orderItem.price || 0);
    const total = parseFloat(orderItem.total || 0);
    const qtyStr = qty.toString().padStart(1, " ");
    const nameWidth = Math.floor(lineWidth * 0.55);
    const nameStr =
      name.length > nameWidth
        ? name.slice(0, nameWidth)
        : name.padEnd(nameWidth, " ");

    output += `${qtyStr} x ${nameStr}${price.toFixed(2).padStart(9, " ")}${total.toFixed(2).padStart(9, " ")}\n`;

    if (orderItem.modifiers && orderItem.modifiers.length) {
      orderItem.modifiers.forEach((extra) => {
        const modPrice = parseFloat(extra.price || 0);
        const modTotal = modPrice * qty;
        const extraName = "+ " + (extra.name || extra.modifier_name || "ND");
        const extraNameWidth = Math.floor(lineWidth * 0.55);
        const extraNameStr =
          extraName.length > extraNameWidth
            ? extraName.slice(0, extraNameWidth)
            : extraName.padEnd(extraNameWidth, " ");

        output += `     ${extraNameStr}${"".padStart(8, " ")}${modTotal.toFixed(2).padStart(9, " ")}\n`;
      });
    }
  });

  output += "-".repeat(lineWidth) + "\n";
  output +=
    "SUBTOTALE".padEnd(labelWidth, " ") +
    parseFloat(order.subtotal || 0).toFixed(2).padStart(valueWidth, " ") +
    "\n";

  if (order.order_type === "dine_in") {
    if (settings.order_serviceenable || settings.order_coveredenable) {
      const serviceLabel = settings.order_serviceenable ? "SERVIZIO" : "COPERTI";
      output +=
        serviceLabel.padEnd(labelWidth, " ") +
        parseFloat(order.covered || 0).toFixed(2).padStart(valueWidth, " ") +
        "\n";
    }
  }

  if (order.discount && order.discount != "0") {
    output +=
      "SCONTO".padEnd(labelWidth, " ") +
      parseFloat(order.discount).toFixed(2).padStart(valueWidth, " ") +
      "\n";
  }

  output += "\n";
  output +=
    "TOTALE".padEnd(labelWidth, " ") +
    parseFloat(order.total || 0).toFixed(2).padStart(valueWidth, " ") +
    "\n\n";

  if (settings.print_date && order.order_date) {
    footer += `${formatDateTime(new Date())}\n`;
  }
  if (order.table) footer += `Tavolo: ${order.table.name}\n\n`;
  if (settings.print_messageline1) footer += `${settings.print_messageline1}\n`;
  if (settings.print_messageline2) footer += `${settings.print_messageline2}\n`;

  return {
    header,
    output,
    footer,
    printableOutput: `${header}${output}${footer}`,
  };
}

module.exports = {
  buildBillTemplate,
};