/*
 * 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.internal.html;

/**
 * Поддержка формата MHT и EML
 */
public class MhtHelper {

    public static com.pullenti.unitext.UnitextDocument _createDoc(byte[] content, com.pullenti.unitext.CreateDocumentParam pars, boolean isMht) throws Exception, java.io.IOException, InterruptedException {
        String txt = com.pullenti.util.MiscHelper.decodeStringUtf8(content, 0, -1);
        return _createDocTxt(txt, pars, isMht, content);
    }

    public static com.pullenti.unitext.UnitextDocument _createDocTxt(String txt, com.pullenti.unitext.CreateDocumentParam pars, boolean isMht, byte[] content) throws Exception, java.io.IOException, InterruptedException {
        int pos = 0;
        com.pullenti.unisharp.Outargwrapper<Integer> wrappos46 = new com.pullenti.unisharp.Outargwrapper<Integer>(pos);
        EmlPart p = EmlPart.tryParse(txt, wrappos46);
        pos = (wrappos46.value != null ? wrappos46.value : 0);
        if (p == null) 
            return null;
        EmlPart p0 = p;
        HtmlNode nod = null;
        java.util.ArrayList<EmlPart> parts = new java.util.ArrayList<EmlPart>();
        parts.add(p);
        java.util.HashMap<String, byte[]> images = new java.util.HashMap<String, byte[]>();
        java.util.HashMap<String, String> imageTypes = new java.util.HashMap<String, String>();
        while (pos < txt.length()) {
            if (txt.charAt(pos) != '-') {
                pos++;
                continue;
            }
            com.pullenti.unisharp.Outargwrapper<Integer> wrappos45 = new com.pullenti.unisharp.Outargwrapper<Integer>(pos);
            p = EmlPart.tryParse(txt, wrappos45);
            pos = (wrappos45.value != null ? wrappos45.value : 0);
            if (p == null) 
                break;
            if (p.contentCharset != null && content != null) {
                try {
                    com.pullenti.util.EncodingWrapper ee = new com.pullenti.util.EncodingWrapper(com.pullenti.util.EncodingStandard.UNDEFINED, p.contentCharset, 0);
                    if (ee != null) {
                        txt = ee.getString(content, 0, -1);
                        return _createDocTxt(txt, pars, isMht, null);
                    }
                } catch (Exception ex) {
                }
            }
            if (p.data != null && p.contentType != null && p.contentType.startsWith("image")) {
                if (pars.onlyForPureText) 
                    continue;
                if (p.filename == null) {
                    int ii = images.size();
                    if (p.contentLocation != null && !images.containsKey(p.contentLocation)) {
                        images.put(p.contentLocation, p.data);
                        if (p.contentType != null) 
                            imageTypes.put(p.contentLocation, p.contentType);
                    }
                    if (p.contentId != null && !images.containsKey("cid:" + p.contentId)) {
                        images.put("cid:" + p.contentId, p.data);
                        if (p.contentType != null) 
                            imageTypes.put("cid:" + p.contentId, p.contentType);
                    }
                    if (images.size() > ii) 
                        continue;
                }
            }
            parts.add(p);
            if (com.pullenti.unisharp.Utils.stringsEq(p.contentType, "text/html")) {
                if (pars.ignoreInnerDocuments) 
                    break;
            }
        }
        com.pullenti.unitext.UnitextDocument doc = null;
        for (int i = 0; i < parts.size(); i++) {
            if (com.pullenti.unisharp.Utils.stringsEq(parts.get(i).contentType, "text/html")) {
                p = parts.get(i);
                if (p.stringData != null) {
                    StringBuilder tmp = new StringBuilder(p.stringData);
                    nod = HtmlParser.parse(tmp, false);
                }
                else if (p.data != null) 
                    nod = HtmlHelper.createNode(null, p.data, p.contentCharset);
                if (nod == null) 
                    continue;
                doc = HtmlHelper.create(nod, null, images, pars);
                if (doc == null) 
                    continue;
                parts.remove(i);
                if (i > 0 && com.pullenti.unisharp.Utils.stringsEq(parts.get(i - 1).contentType, "text/plain")) 
                    parts.remove(i - 1);
                break;
            }
        }
        if (doc == null) {
            for (int i = 0; i < parts.size(); i++) {
                if (com.pullenti.unisharp.Utils.stringsEq(parts.get(i).contentType, "text/plain")) {
                    if (parts.get(i).stringData != null) {
                        doc = com.pullenti.unitext.UnitextService.createDocumentFromText(parts.get(i).stringData);
                        parts.remove(i);
                        break;
                    }
                }
            }
        }
        if (doc == null) 
            doc = new com.pullenti.unitext.UnitextDocument();
        doc.sourceFormat = (isMht ? com.pullenti.unitext.FileFormat.MHT : com.pullenti.unitext.FileFormat.EML);
        for (java.util.Map.Entry<String, String> a : p0.attrs.entrySet()) {
            if (!doc.attrs.containsKey(a.getKey())) 
                doc.attrs.put(a.getKey(), a.getValue());
        }
        if (!isMht) {
            int kk = 0;
            com.pullenti.unitext.internal.uni.UnitextGen gen = new com.pullenti.unitext.internal.uni.UnitextGen();
            for (String s : new String[] {"From", "To", "CC", "Date", "Subject"}) {
                if (doc.attrs.containsKey(s)) {
                    gen.appendText((s + ": " + doc.attrs.get(s)), false);
                    gen.appendNewline(false, false);
                    kk++;
                }
            }
            if (kk > 0) {
                gen.appendNewline(false, false);
                if (doc.content != null) 
                    gen.append(doc.content, null, -1, false);
                doc.content = gen.finish(true, null);
                doc.optimize(false, null);
                doc.refreshParents();
            }
        }
        if (pars.ignoreInnerDocuments) 
            return doc;
        for (EmlPart pp : parts) {
            if (pp.data != null) {
                if (pp.filename != null) {
                    try {
                        com.pullenti.unitext.UnitextDocument aa = com.pullenti.unitext.UnitextService.createDocument(pp.filename, pp.data, pars);
                        if (aa != null) 
                            doc.innerDocuments.add(aa);
                    } catch (Exception ex) {
                    }
                }
            }
        }
        return doc;
    }

    public static String _encodeString(String val) {
        StringBuilder res = new StringBuilder();
        int col = 0;
        for (int i = 0; i < val.length(); i++) {
            char ch = val.charAt(i);
            if (ch == '\r' || ch == '\n') 
                col = 0;
            else 
                col++;
            if (col > 80) {
                res.append("=\r\n");
                col = 0;
            }
            if (ch == '=') 
                res.append("=3D");
            else 
                res.append(ch);
        }
        return res.toString();
    }

    public static String _decodeString(String val) {
        if (com.pullenti.unisharp.Utils.isNullOrEmpty(val) || (val.length() < 3)) 
            return val;
        if (val.length() < 10) 
            return val;
        if (!(val.indexOf("=?") >= 0)) 
            return val;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < val.length(); i++) {
            if (val.charAt(i) == '=' && ((i + 1) < val.length()) && val.charAt(i + 1) == '?') {
                int j;
                i += 2;
                for (j = i; j < val.length(); j++) {
                    if (val.charAt(j) == '?') 
                        break;
                }
                if (j >= val.length()) 
                    return val;
                String charset = val.substring(i, i + j - i).trim();
                com.pullenti.util.EncodingWrapper enc = null;
                try {
                    enc = new com.pullenti.util.EncodingWrapper(com.pullenti.util.EncodingStandard.UNDEFINED, charset, 0);
                } catch (Exception ex) {
                    return val;
                }
                i = j + 1;
                char typ = '?';
                for (++j; j < val.length(); j++) {
                    if (val.charAt(j) == '?') 
                        break;
                    else if (val.charAt(j) == 'Q' || val.charAt(j) == 'q') 
                        typ = 'Q';
                    else if (val.charAt(j) == 'B' || val.charAt(j) == 'b') 
                        typ = 'B';
                }
                if (typ != 'Q' && typ != 'B') 
                    return val;
                i = j + 1;
                for (++j; j < val.length(); j++) {
                    if (val.charAt(j) == '?' && ((j + 1) < val.length()) && val.charAt(j + 1) == '=') 
                        break;
                }
                String data = val.substring(i, i + j - i).trim();
                byte[] bdata = null;
                if (typ == 'B') 
                    bdata = java.util.Base64.getDecoder().decode((data).replace("\r", "").replace("\n", ""));
                else {
                    java.util.ArrayList<Byte> bbb = new java.util.ArrayList<Byte>();
                    for (int k = 0; k < data.length(); k++) {
                        if (data.charAt(k) != '=' || (k + 1) >= data.length()) 
                            bbb.add((byte)data.charAt(k));
                        else if ((k + 2) < data.length()) {
                            int v1 = EmlPart._toInt(data.charAt(k + 1));
                            int v2 = EmlPart._toInt(data.charAt(k + 2));
                            if (v1 >= 0 && v2 >= 0) {
                                bbb.add((byte)(((v1 << 4) | v2)));
                                k += 2;
                            }
                            else 
                                bbb.add((byte)data.charAt(k));
                        }
                    }
                    bdata = com.pullenti.unisharp.Utils.toBytesArray(bbb.toArray(new Byte[bbb.size()]));
                }
                if (bdata == null) 
                    return val;
                String ooo = enc.getString(bdata, 0, -1);
                res.append(ooo);
                i = j + 1;
            }
            else 
                res.append(val.charAt(i));
        }
        return res.toString();
    }

    public static String _corrString(String val) {
        if (com.pullenti.unisharp.Utils.isNullOrEmpty(val) || (val.length() < 3)) 
            return val;
        int i = val.indexOf(';');
        if (i > 0) 
            val = val.substring(0, 0 + i).trim();
        if (val.charAt(0) == '"' && val.charAt(val.length() - 1) == '"') 
            val = val.substring(1, 1 + val.length() - 2);
        return val;
    }
    public MhtHelper() {
    }
}
