package com.brilliance.isc.swift.objmtconvert.util;

import com.brilliance.swift.util.StringUtil;
import com.brilliance.swift.util.SwiftTransferUtil;
import com.prowidesoftware.swift.model.MxId;
import com.prowidesoftware.swift.model.mx.NamespaceReader;

import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gechengyang
 * @date 2023/2/14
 */
public class MXUtil {
    public static String getSwiftType(String jsonData) {
        Map map = JsonUtil.json2Map(jsonData);
        String msgType = (String) map.get(Constans.IDENTIFIER);
        return msgType;
    }

    public static boolean isCOV(String jsonData) {
        Map map = JsonUtil.json2Map(jsonData);
        if (map.get("undrlygCstmrCdtTrf") != null) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean validateMx(String xml) {
        //1.获取AppHdr报文内容，根据@xmlns获取版本对应的xsd文件
        String regex = "(\\<([\\w]*:)?AppHdr[\\w\\W]*\\<\\/([\\w]*:)?AppHdr\\>)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(xml);
        String appHdrXml = "";
        if (m.find()) {
            appHdrXml = m.group(1);
        }
        String appHdrXsdName = null;
        Optional<String> namespace = NamespaceReader.findAppHdrNamespace(xml);
        if (namespace.isPresent()) {
            MxId appHdrMxId = new MxId(namespace.get());
            appHdrXsdName = appHdrMxId.getBusinessProcess().name()
                    + appHdrMxId.getFunctionality()
                    + appHdrMxId.getVariant()
                    + appHdrMxId.getVersion();
        }
        if (StringUtil.isNotEmpty(appHdrXsdName) && StringUtil.isNotEmpty(appHdrXml)) {
            SwiftTransferUtil.schemaValidate(appHdrXsdName, appHdrXml);
        }
        //2.获取Document报文内容，根据@xmlns获取版本对应的xsd文件
        regex = "(\\<([\\w]*:)?Document[\\w\\W]*\\<\\/([\\w]*:)?Document\\>)";
        p = Pattern.compile(regex);
        m = p.matcher(xml);
        String documentXml = "";
        if (m.find()) {
            documentXml = m.group(1);
        }
        String documentXsdName = "";
        namespace = NamespaceReader.findDocumentNamespace(xml);
        if (namespace.isPresent()) {
            MxId documentMxId = new MxId(namespace.get());
            documentXsdName = documentMxId.getBusinessProcess().name()
                    + documentMxId.getFunctionality()
                    + documentMxId.getVariant()
                    + documentMxId.getVersion();
        }
        if (StringUtil.isNotEmpty(documentXsdName) && StringUtil.isNotEmpty(documentXml)) {
            SwiftTransferUtil.schemaValidate(documentXsdName, documentXml);
        }
        return true;
    }

}
