/*
 * SDK Pullenti Unitext, version 4.33, fabruary 2026. Copyright (c) 2013-2026, Pullenti. All rights reserved. 
 * Non-Commercial Freeware and Commercial Software. 
 * This class is generated using the converter Unisharping (www.unisharping.ru) from Pullenti C# project. 
 * The latest version of the code is available on the site www.pullenti.ru
 */

package com.pullenti.unitext;

/**
 * Картинка
 */
public class UnitextImage extends UnitextItem {

    /**
     * Содержимое картинки (может быть null)
     */
    public byte[] content;

    /**
     * Ширина (в единицах исходного файла)
     */
    public String width;

    /**
     * Высота (в единицах исходного файла)
     */
    public String height;

    /**
     * Ссылка на слой тексто-графического представления (если есть)
     */
    public UnilayRectangle rect;

    /**
     * Это извне устанавливаемый URI на картинку (для функции GetHtml)
     */
    public String htmlSrcUri;

    @Override
    public UnitextItem clone() {
        UnitextImage res = new UnitextImage();
        res._cloneFrom(this);
        res.content = content;
        res.width = width;
        res.height = height;
        res.rect = rect;
        res.htmlSrcUri = htmlSrcUri;
        return res;
    }

    @Override
    public String getInnerTag() {
        return "img";
    }


    @Override
    public String toString() {
        StringBuilder tmp = new StringBuilder();
        tmp.append("Image");
        if (width != null || height != null) 
            tmp.append(" ").append(((width != null ? width : "?"))).append(" x ").append(((height != null ? height : "?")));
        if (content != null) {
            FileFormat frm = com.pullenti.util.FileFormatsHelper.analizeFormat(null, content);
            if (frm != FileFormat.UNKNOWN) 
                tmp.append(" ").append(frm.toString().toUpperCase());
            tmp.append(" ").append(content.length).append("bytes");
        }
        else if (htmlSrcUri != null) 
            tmp.append(" ").append(htmlSrcUri);
        return tmp.toString();
    }

    @Override
    public void getPlaintext(StringBuilder res, GetPlaintextParam pars) {
        if (pars != null && pars.setPositions) 
            beginChar = res.length();
        String templ = (pars == null ? "[Картинка%1]" : pars.imageTemplate);
        res.append(templ.replace("%1", (content == null ? "" : ((Integer)content.length).toString())));
        if (pars != null && pars.setPositions) 
            endChar = beginChar;
    }

    @Override
    public void getHtml(StringBuilder res, GetHtmlParam par) {
        try {
            if (par != null && !par.callBefore(this, res)) 
                return;
            res.append("<img");
            if (id != null) 
                res.append(" id=\"").append(id).append("\"");
            res.append(" style=\"max-width:100%;");
            if (width != null && width.endsWith("pt")) {
                int nn;
                com.pullenti.unisharp.Outargwrapper<Integer> wrapnn610 = new com.pullenti.unisharp.Outargwrapper<Integer>();
                boolean inoutres611 = com.pullenti.unisharp.Utils.parseInteger(width.substring(0, 0 + width.length() - 2), 0, null, wrapnn610);
                nn = (wrapnn610.value != null ? wrapnn610.value : 0);
                if (inoutres611) {
                    if (nn > 1000) 
                        res.append("width:100%;");
                }
            }
            boolean over = false;
            if (content == null) 
                res.append("border:2pt solid red;");
            else if (content.length > 10000000 || ((par != null && content.length > par.maxImageSize)) || ((res.length() > 40000000 && content.length > 10000))) {
                res.append("border:2pt solid red;");
                over = true;
            }
            int wi = 0;
            int hi = 0;
            if (width != null) {
                for (int i = 0; i < width.length(); i++) {
                    if (!Character.isDigit(width.charAt(i))) 
                        break;
                    else 
                        wi = com.pullenti.unisharp.Utils.parseInteger(width.substring(0, 0 + i + 1), 0, null);
                }
            }
            if (height != null) {
                for (int i = 0; i < height.length(); i++) {
                    if (!Character.isDigit(height.charAt(i))) 
                        break;
                    else 
                        hi = com.pullenti.unisharp.Utils.parseInteger(height.substring(0, 0 + i + 1), 0, null);
                }
            }
            if ((wi < 500) && (hi < 500)) {
                if (width != null) 
                    res.append("width:").append(width).append(";");
                if (height != null) 
                    res.append("height:").append(height).append(";");
            }
            res.append("\"");
            if (content != null) {
                if (over) 
                    res.append(" alt=\"Image too large to show here (").append((content.length / 1024)).append("Kb)\"");
                else {
                    FileFormat frm = com.pullenti.util.FileFormatsHelper.analizeFormat(null, content);
                    if (frm == FileFormat.JPG2000) 
                        res.append(" title=\"Image format JPEG 2000 not supported\"");
                    else {
                        String base64 = new String(java.util.Base64.getEncoder().encode(content));
                        if (base64.indexOf('\n') >= 0) 
                            base64 = base64.replace("\n", "");
                        String str = null;
                        if (frm != FileFormat.UNKNOWN) {
                            str = com.pullenti.util.FileFormatsHelper.getFormatExt(frm);
                            if (str.startsWith(".")) 
                                str = str.substring(1);
                        }
                        if (str == null) 
                            str = "png";
                        if (com.pullenti.unisharp.Utils.stringsEq(str, "tif")) 
                            str = "tiff";
                        String src = ("data:image/" + str + ";base64,") + base64;
                        res.append(" src=\"").append(src).append("\"");
                    }
                }
            }
            else 
                res.append(" src=\"").append(((htmlSrcUri != null ? htmlSrcUri : "undefined"))).append("\"");
            res.append("/>");
            if (par != null) 
                par.callAfter(this, res);
        } catch (Exception ex123) {
        }
    }

    @Override
    public void getXml(com.pullenti.unisharp.XmlWriterWrapper xml) throws javax.xml.stream.XMLStreamException {
        xml.wr.writeStartElement("image");
        this._writeXmlAttrs(xml);
        if (width != null) 
            xml.wr.writeAttribute("width", width);
        if (height != null) 
            xml.wr.writeAttribute("height", height);
        if (htmlSrcUri != null) 
            xml.wr.writeAttribute("uri", com.pullenti.util.MiscHelper.correctXmlValue(htmlSrcUri));
        if (content != null) {
            try {
                String dat = new String(java.util.Base64.getEncoder().encode(content));
                StringBuilder tmp = new StringBuilder();
                int i = 0;
                for (char ch : dat.toCharArray()) {
                    if (com.pullenti.unisharp.Utils.isWhitespace(ch)) 
                        continue;
                    tmp.append(ch);
                    if ((++i) >= 100) {
                        i = 0;
                        tmp.append("\r\n");
                    }
                }
                xml.wr.writeCharacters(tmp.toString());
            } catch (Exception ex) {
                System.gc();
            }
        }
        xml.wr.writeEndElement();
    }

    @Override
    public void fromXml(org.w3c.dom.Node xml) throws NumberFormatException {
        super.fromXml(xml);
        if (xml.getAttributes() != null) {
            for (org.w3c.dom.Node a : (new com.pullenti.unisharp.XmlAttrListWrapper(xml.getAttributes())).arr) {
                if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(a), "width")) 
                    width = a.getNodeValue();
                else if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(a), "height")) 
                    height = a.getNodeValue();
                else if (com.pullenti.unisharp.Utils.stringsEq(com.pullenti.unisharp.Utils.getXmlLocalName(a), "uri")) 
                    htmlSrcUri = a.getNodeValue();
            }
        }
        try {
            String txt = xml.getTextContent();
            if (txt != null) 
                content = java.util.Base64.getDecoder().decode((txt).replace("\r", "").replace("\n", ""));
        } catch (Exception ex612) {
        }
    }

    @Override
    public void setDefaultTextPos(com.pullenti.unisharp.Outargwrapper<Integer> cp, StringBuilder res) {
        beginChar = (endChar = cp.value);
        cp.value++;
        if (res != null) 
            res.append(' ');
    }

    public static UnitextImage _new96(String _arg1) {
        UnitextImage res = new UnitextImage();
        res.id = _arg1;
        return res;
    }

    public static UnitextImage _new278(byte[] _arg1) {
        UnitextImage res = new UnitextImage();
        res.content = _arg1;
        return res;
    }

    public static UnitextImage _new355(byte[] _arg1, UnilayRectangle _arg2, String _arg3) {
        UnitextImage res = new UnitextImage();
        res.content = _arg1;
        res.rect = _arg2;
        res.pageSectionId = _arg3;
        return res;
    }

    public static UnitextImage _new356(String _arg1) {
        UnitextImage res = new UnitextImage();
        res.pageSectionId = _arg1;
        return res;
    }
    public UnitextImage() {
        super();
    }
}
