package com.Modules.NormalData;
import com.common.entity.RuleContent.Cropper_paramsType;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import com.common.entity.SyslogMessage;
import com.common.util.JsonParser;
import com.common.util.SyslogParser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.common.service.DmNormalizeRuleService;
import com.common.service.DmColumnService;

import java.util.List;
import java.util.Map;
import com.common.util.StringExtractorUtil;
import com.common.entity.RuleContent.kv_paramsType;


public class logNormalData {

    private static final Logger logger = LoggerFactory.getLogger(logNormalData.class);

    private String  strLogMsg  ;
    private Map<String, Object> messageMap ;
    @Autowired
    public DmNormalizeRuleService dmNormalizeRuleService =new DmNormalizeRuleService();
    @Autowired
    public DmColumnService dmColumnService  ;

    public  logNormalData( String LogMsg) {

        strLogMsg=LogMsg;
        /** 处理步骤 */
        //初始化 （获取syslog_normal_data 表全部字段的属性、设备ID对应的规则设置、转化成JSON）
        //判断数据解析类型（json、键值、xml、正则表达式、分割符）解析syslogMessage 字段转成 HashMAP
        //匹配规则内容，获取字段映射关系配置，抽取命中的字段名称、数值
        //判断字段内容及类型，根据数据类型属性，进行内容转换。
        //生成insert SQL语句、执行入库操作。
    }

    public    Map<String, Object>  getMessageToMap( String MsgContent)
    {
        //解析SyslogMessage
        SyslogMessage msg = SyslogParser.parse(MsgContent);
        System.out.println("解析结果-log content: " + msg.getMessage().toString());
        Map<String, Object> flatMap = JsonParser.parseJsonToFlatMap(msg.getMessage().toString());
        flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
        List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
        return flatMap;
    }


    public     List<Map<String, Object>> getRuleList( long  device_id)
    {
        List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
        if (rulelst!=null)
        {
            System.out.println("rulelst: " + rulelst);
        }
        return rulelst;
    }

    /**
     *  解析数据项内容，Json格式类型
     * @param MsgContent
     * @param cropperParams
     * @return
     */
    public static String  ParserMessageJsonType(String  MsgContent , Cropper_paramsType cropperParams)
    {
        System.out.println("ParserMessageJsonType  MsgContent:" +MsgContent );
        if(cropperParams ==null) {
           return  removeBOM(JsonParser.extractJsonFromLogMessage(MsgContent));
        }
        String strJson ="";
        if(cropperParams.gettail_key().equals("") && cropperParams.gettail_offset()==0 ) {
             strJson = StringExtractorUtil.extractFromStartToEnd(MsgContent, cropperParams.gethead_key(), cropperParams.gethead_offset());
            System.out.println("ParserMessageJsonType extractFromStartToEnd strJson" +strJson );
        }
        else {
            strJson= StringExtractorUtil.extract(MsgContent,cropperParams.gethead_key(),cropperParams.gethead_offset(),cropperParams.gettail_key(),cropperParams.gettail_offset() );
            //return removeBOM(MsgContent).trim();
        }
        return removeBOM(strJson).trim();
    }

    public static String removeBOM(String s) {
        if (s != null && s.startsWith("\uFEFF")) {
            return s.substring(1);
        }
        return s;
    }


    //获取数据泛化规则的rule_content列表字段，kv类型提取 kv_params 节点值
    public static kv_paramsType  getkv_paramsType( Map<String, Object> dmNormalizeRule )
    {
        kv_paramsType  kvParams = new kv_paramsType();
        try {
            JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
            if (jsonObject.isEmpty()) return null;
            kvParams.setInternal(jsonObject.getJSONObject("kv_params").get("internal").toString());
            kvParams.setExternal(jsonObject.getJSONObject("kv_params").get("external").toString());
            kvParams.setL_trim(jsonObject.getJSONObject("kv_params").get("l_trim").toString());
            kvParams.setR_trim( jsonObject.getJSONObject("kv_params").get("r_trim").toString());
            return kvParams;
        }catch (Exception ex) {
            logger.error("getkv_paramsType："+ex.getMessage());
            return null;
        }
    }
    //获取数据泛化规则的rule_content列表字段，sep类型提取 sep 节点值（分隔符）
    public static String sepType( Map<String, Object> dmNormalizeRule )
    {

        try {
            JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
            if (jsonObject.isEmpty()) return null;
            return   jsonObject.get("sep").toString();
        }catch (Exception ex) {
            logger.error("regexp："+ex.getMessage());
            return null;
        }
    }

    //获取数据泛化规则的rule_content列表字段，regex类型提取 regexp 节点值（分隔符）
    public static String Regexp ( Map <String, Object> dmNormalizeRule )
    {

        try {
            JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
            if (jsonObject.isEmpty()) return null;
            return   jsonObject.get("regexp").toString();
        }catch (Exception ex) {
            logger.error("sepType："+ex.getMessage());
            return null;
        }
    }
    public static void main(String[] args) {

        String strlogMessage= "<14>1 2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - ﻿{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
        String strMsgContent= "﻿{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
        //Map<String, Object> flatMap  =(new logNormalData()).getMessageToMap(strMsgContent);
        //flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
        logNormalData  logData =new logNormalData( strlogMessage);
        Cropper_paramsType cropperParams =new Cropper_paramsType();
        cropperParams.settail_offset(0);
        cropperParams.settail_key("");
        cropperParams.sethead_key("{");
        cropperParams.sethead_offset(-1);
        String str= ParserMessageJsonType(strlogMessage,cropperParams);
        System.out.println("parser msg:"+str);

        //List<Map<String, Object>> rulelst= logData.getRuleList(1);


    }
}



