/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2025, Arnaud Roques
 *
 * Project Info:  https://plantuml.com
 * 
 * If you like this project or if you find it useful, you can support us at:
 * 
 * https://plantuml.com/patreon (only 1$ per month!)
 * https://plantuml.com/paypal
 * 
 * This file is part of PlantUML.
 *
 * PlantUML is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PlantUML distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 *
 * Original Author:  Arnaud Roques
 *
 *
 */
package net.sourceforge.plantuml;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import net.sourceforge.plantuml.braille.BrailleCharFactory;
import net.sourceforge.plantuml.braille.UGraphicBraille;
import net.sourceforge.plantuml.cli.GlobalConfig;
import net.sourceforge.plantuml.cli.GlobalConfigKey;
import net.sourceforge.plantuml.klimt.drawing.debug.StringBounderDebug;
import net.sourceforge.plantuml.klimt.drawing.svg.SvgGraphics;
import net.sourceforge.plantuml.klimt.font.StringBounder;
import net.sourceforge.plantuml.klimt.font.StringBounderRaw;
import net.sourceforge.plantuml.klimt.font.UFont;
import net.sourceforge.plantuml.klimt.font.UFontImpl;
import net.sourceforge.plantuml.klimt.geom.XDimension2D;
import net.sourceforge.plantuml.log.Logme;
import net.sourceforge.plantuml.png.MetadataTag;
import net.sourceforge.plantuml.security.SFile;
import net.sourceforge.plantuml.teavm.StringBounderTeaVM;
import net.sourceforge.plantuml.teavm.TeaVM;
import net.sourceforge.plantuml.text.SvgCharSizeHack;

/**
 * Format for output files generated by PlantUML.
 * 
 * @author Arnaud Roques
 * 
 */
public enum FileFormat {

	EPS("eps", "application/postscript"), //
	EPS_TEXT("eps-text", "application/postscript"), //
	ATXT("txt", "text/plain"), //
	UTXT("utxt", "text/plain;charset=UTF-8"), //
	XMI_STANDARD("xmi", "application/vnd.xmi+xml"), //
	XMI_STAR("xmi-star", "application/vnd.xmi+xml"), //
	XMI_ARGO("xmi-argo", "application/vnd.xmi+xml"), //
	XMI_CUSTOM("xmi-custom", "application/vnd.xmi+xml"), //
	XMI_SCRIPT("xmi-script", "application/vnd.xmi+xml"), //
	SCXML("scxml", "application/scxml+xml"), //
	GRAPHML("graphml", "application/graphml+xml"), //
	PDF("pdf", "application/pdf"), //
	HTML("html", "text/html"), //
	HTML5("html5", "text/html"), //
	VDX("vdx", "application/vnd.visio.xml"), //
	LATEX("eps", "application/x-latex"), //
	LATEX_NO_PREAMBLE("eps-no-preamble", "application/x-latex"), //
	BASE64("base64", "text/plain; charset=x-user-defined"), //
	BRAILLE_PNG("braille-png", "image/png"), //
	OBFUSCATE("obfuscate", "text/plain"), //
	DEBUG("debug", "text/plain"), //

	PREPROC("preproc", "text/plain"), //
	PNG("png", "image/png"), //
	PNG_EMPTY("png-empty", "image/png"), //
	RAW("raw", "image/raw"), //
	SVG("svg", "image/svg+xml"); //

	private final String mimeType;
	private final String name;
	private final static Map<String, FileFormat> byName;

	static {
		byName = new HashMap<>();
		for (FileFormat format : values())
			byName.put(format.name, format);
	}

	public static FileFormat fromCli(String formatName) {
		return byName.get(formatName);
	}

	private FileFormat(String name, String mimeType) {
		this.mimeType = mimeType;
		this.name = name;
	}

	public String getMimeType() {
		return mimeType;
	}

	/**
	 * Returns the file format to be used for that format.
	 * 
	 * @return a string starting by a point.
	 */
	public String getFileSuffix() {
		if (!TeaVM.isTeaVM()) {
			if (name().startsWith("XMI_CUSTOM"))
				return ".xmi_custom";

			if (name().startsWith("XMI"))
				return ".xmi";

			if (this == LATEX || this == LATEX_NO_PREAMBLE)
				return ".tex";

			if (this == BRAILLE_PNG)
				return ".braille.png";

			if (this == EPS_TEXT)
				return EPS.getFileSuffix();
		}

		return "." + StringUtils.goLowerCase(name());
	}

	final static private BufferedImage imDummy = TeaVM.isTeaVM() ? null
			: new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
	final static public Graphics2D gg = TeaVM.isTeaVM() ? null : imDummy.createGraphics();
	static {
		if (!TeaVM.isTeaVM()) {
			gg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			gg.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
		}
	}

	public StringBounder getDefaultStringBounder() {
		return getDefaultStringBounder(TikzFontDistortion.getDefault(), SvgCharSizeHack.NO_HACK);
	}

	public StringBounder getDefaultStringBounder(TikzFontDistortion tikzFontDistortion, SvgCharSizeHack charSizeHack) {
		// ::comment when JAVA8
		if (TeaVM.isTeaVM()) {
			return new StringBounderTeaVM();
		}
		// ::done

		if (this == LATEX || this == LATEX_NO_PREAMBLE)
			return getTikzStringBounder(tikzFontDistortion);

		if (this == BRAILLE_PNG)
			return getBrailleStringBounder();

		if (this == DEBUG)
			return new StringBounderDebug();

		if (this == SVG)
			return getSvgStringBounder(charSizeHack);

		return getNormalStringBounder();
	}

	private static final int CACHE_SIZE = 10_000;

	private static final Map<FontTextKey, XDimension2D> DIMENSION_CACHE = new LinkedHashMap<FontTextKey, XDimension2D>(
			CACHE_SIZE, 0.75f, true) {
		@Override
		protected boolean removeEldestEntry(Map.Entry<FontTextKey, XDimension2D> eldest) {
			return size() > CACHE_SIZE;
		}
	};

	private static class FontTextKey {
		private final UFont font;
		private final String text;

		FontTextKey(UFont font, String text) {
			this.font = font;
			this.text = text;
		}

		@Override
		public boolean equals(Object obj) {
			final FontTextKey other = (FontTextKey) obj;
			return font.equals(other.font) && text.equals(other.text);
		}

		@Override
		public int hashCode() {
			return font.hashCode() * 31 + text.hashCode();
		}
	}

	// ::comment when __TEAVM__
	static private XDimension2D getJavaDimension(UFont font, String text) {
		if (text.length() == 0)
			return new XDimension2D(0, 0);

		final FontTextKey key = new FontTextKey(font, text);

		synchronized (DIMENSION_CACHE) {
			XDimension2D cached = DIMENSION_CACHE.get(key);
			if (cached != null)
				return cached;

			final Font javaFont = UFontImpl.getUnderlayingFont(font, text);
			final FontMetrics fm = gg.getFontMetrics(javaFont);
			final Rectangle2D rect = fm.getStringBounds(text, gg);
			final XDimension2D result = new XDimension2D(rect.getWidth(), rect.getHeight());
			DIMENSION_CACHE.put(key, result);
			return result;
		}
	}

	private StringBounder getSvgStringBounder(final SvgCharSizeHack charSizeHack) {
		return new StringBounderRaw(FileFormat.gg.getFontRenderContext()) {
			public String toString() {
				return "FileFormat::getSvgStringBounder";
			}

			protected XDimension2D calculateDimensionInternal(UFont font, String text) {
				text = charSizeHack.transformStringForSizeHack(text);
				return getJavaDimension(font, text);
			}

			public boolean matchesProperty(String propertyName) {
				return "SVG".equalsIgnoreCase(propertyName);
			}

		};
	}

	private StringBounder getNormalStringBounder() {
		return new StringBounderRaw(FileFormat.gg.getFontRenderContext()) {
			public String toString() {
				return "FileFormat::getNormalStringBounder";
			}

			protected XDimension2D calculateDimensionInternal(UFont font, String text) {
				return getJavaDimension(font, text);
			}

			public boolean matchesProperty(String propertyName) {
				return false;
			}

		};
	}

	private StringBounder getBrailleStringBounder() {
		return new StringBounderRaw(FileFormat.gg.getFontRenderContext()) {
			public String toString() {
				return "FileFormat::getBrailleStringBounder";
			}

			protected XDimension2D calculateDimensionInternal(UFont font, String text) {
				final int nb = BrailleCharFactory.build(text).size();
				final double quanta = UGraphicBraille.QUANTA;
				final double height = 5 * quanta;
				final double width = 3 * nb * quanta + 1;
				return new XDimension2D(width, height);
			}

			@Override
			public double getDescent(UFont font, String text) {
				return UGraphicBraille.QUANTA;
			}

			public boolean matchesProperty(String propertyName) {
				return false;
			}

		};
	}

	private StringBounder getTikzStringBounder(final TikzFontDistortion tikzFontDistortion) {
		return new StringBounderRaw(FileFormat.gg.getFontRenderContext()) {

			private final LatexManager latexManager = new LatexManager(tikzFontDistortion.getTexSystem(),
					tikzFontDistortion.getTexPreamble());

			public String toString() {
				return "FileFormat::getTikzStringBounder";
			}

			protected XDimension2D calculateDimensionInternal(UFont font, String text) {
				double[] widthHeightDepth = latexManager.getWidthHeightDepth(styleText(font, text));
				double height = widthHeightDepth[1] + widthHeightDepth[2];
				if (height == 0.0 && text.trim().isEmpty()) {
					// avoid return 0 height for space, otherwise cause exception, case in #1259
					height = latexManager.getWidthHeightDepth(styleText(font, " "))[0];
				}
				return new XDimension2D(widthHeightDepth[0], height);
			}

			public boolean matchesProperty(String propertyName) {
				return "TIKZ".equalsIgnoreCase(propertyName);
			}

			public double getDescent(UFont font, String text) {
				double[] widthHeightDepth = latexManager.getWidthHeightDepth(styleText(font, text));
				return widthHeightDepth[2];
			}

			protected String styleText(UFont font, String text) {
				if (font == null) {
					return "$" + text + "$";
				}
				StringBuilder sb = new StringBuilder();
				final boolean italic = font.isItalic();
				final boolean bold = font.isBold();

				if (italic)
					sb.append("\\textit{");

				if (bold)
					sb.append("\\textbf{");

				sb.append(LatexManager.protectText(text));
				if (bold)
					sb.append("}");

				if (italic)
					sb.append("}");

				return sb.toString();
			}
		};
	}

	/**
	 * Check if this file format is Encapsulated PostScript.
	 * 
	 * @return <code>true</code> for EPS.
	 */
	public boolean isEps() {
		if (this == EPS)
			return true;

		if (this == EPS_TEXT)
			return true;

		return false;
	}

	public String changeName(String fileName, int cpt) {
		if (cpt == 0)
			return changeName(fileName, getFileSuffix());

		return changeName(fileName, (String) GlobalConfig.getInstance().value(GlobalConfigKey.FILE_SEPARATOR)
				+ String.format("%03d", cpt) + getFileSuffix());
	}

	private String changeName(String fileName, String replacement) {
		String result = fileName.replaceAll("\\.\\w+$", replacement);
		if (result.equals(fileName))
			result = fileName + replacement;

		return result;
	}

	public boolean doesSupportMetadata() {
		return this == PNG || this == SVG;
	}

	private static final String META_HEADER_NEW = "<?plantuml-src ";

	public boolean equalsMetadata(String currentMetadata, SFile existingFile) {
		try {
			if (this == PNG) {
				final MetadataTag tag = new MetadataTag(existingFile, "plantuml");
				final String previousMetadata = tag.getData();
				final boolean sameMetadata = currentMetadata.equals(previousMetadata);
				return sameMetadata;
			}
			if (this == SVG) {
				final String svg = FileUtils.readSvg(existingFile);
				if (svg == null)
					return false;

				final String currentSignature = SvgGraphics.getMetadataHex(currentMetadata);

				// New format: <?plantuml-src ...?>
				final int idxNew = svg.lastIndexOf(META_HEADER_NEW);
				if (idxNew != -1) {
					final String part = svg.substring(idxNew + META_HEADER_NEW.length());
					return part.startsWith(currentSignature + "?>");
				}

				// Old format: <!--SRC=[...]-->
				final int idxOld = svg.lastIndexOf(SvgGraphics.META_HEADER);
				if (idxOld != -1) {
					final String part = svg.substring(idxOld + SvgGraphics.META_HEADER.length());
					return part.startsWith(currentSignature + "]");
				}
			}
		} catch (IOException e) {
			Logme.error(e);
		}
		return false;
	}
	// ::done

}
