import { Type } from "./type_utils.ts";
import { escapeXML, capitalize } from "./utils.ts";

const typeToFPRGType: Record<Type, string> = {
  int: "Integer",
  float: "Real",
  string: "String",
  boolean: "Boolean",
}

export function declare (name: string, type: Type): string {
  return `<declare `
    + `name="${name}" `
    + `type="${typeToFPRGType[type]}" `
    + `array="False" `
    + `size=""/>\n`;
}

export function assign (variable: string, expr: string): string {
  return `<assign `
    + `variable="${variable}" `
    + `expression="${escapeXML(expr)}"/>\n`;
}

export function output (expr: string, newline: boolean): string {
  return `<output `
    + `expression="${escapeXML(expr)}" `
    + `newline="${capitalize(newline.toString())}"/>\n`;
}

export function input (variable: string): string {
  return `<input `
    + `variable="${variable}"/>\n`;
}

export function comment (text: string): string {
  return `<comment text="${escapeXML(text)}"/>\n`;
}

export function _if (
  indent: string,
  expr: string,
  arm1: string,
  arm2?: string
): string {
  const exIndent = indent + "    ";
  return `${indent}<if expression="${escapeXML(expr)}">\n`
    + `${exIndent}<then>\n${arm1}${exIndent}</then>\n`
    + `${exIndent}<else>\n${arm2 ?? ""}${exIndent}</else>\n`
    + `${indent}</if>\n`;
}

export function _while (
  indent: string,
  expr: string,
  arm: string
): string {
  return `${indent}<while expression="${escapeXML(expr)}">\n`
    + `${arm}${indent}</while>\n`;
}

export function _for (
  indent: string,
  variable: string,
  start: number,
  end: number,
  direction: "inc" | "dec",
  step: number,
  body: string
): string {
  return `${indent}<for `
    + `variable="${variable}" `
    + `start="${start}" `
    + `end="${end}" `
    + `direction="${direction}" `
    + `step="${step}">\n`
    + `${body}${indent}</for>\n`;
}