package com.mortals.xhx.daemon.applicationservice;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.springcloud.service.IApplicationStartedService;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.daemon.applicationservice.model.DestInfo;
import lombok.extern.slf4j.Slf4j;
import org.pcap4j.core.PcapAddress;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.Pcaps;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

//@Component
@Slf4j
public class CaptureStartedService implements IApplicationStartedService {
    @Override
    public void start() {
        log.info("启动抓取网卡数据服务..");
        ThreadPool.getInstance().init(20);

        List<PcapNetworkInterface> allDevs = null;
        try {
            allDevs = Pcaps.findAllDevs();
            for (final PcapNetworkInterface device : allDevs) {
                String localHost = "127.0.0.1";
                List<PcapAddress> addresses = device.getAddresses();
                Boolean bool=false;
                for (PcapAddress pcapAddress : addresses) {
                    // 获取网卡IP地址
                    String ip = pcapAddress.getAddress().getHostAddress();
                   // log.info("device"+JSON.toJSONString(device) + " ip:" + ip+" is local ipw:"+ JSON.toJSONString( NetUtil.localIps()));
                    //非本地网卡
                    boolean ipv4 = Validator.isIpv4(ip);
                  //  log.info("deviceName:{},ip:{}, is ipv4:{}",device.getName(),ip ,ipv4);
                    if (ip != null && ip.contains(localHost)) {
                        bool=true;
                        break;
                        // 返回指定的设备对象
                        //return networkInterface;
                    }
                    if(!ipv4){
                        bool=true;
                        break;
                    }
                }
                if ("any".indexOf(device.getName()) != -1) {
                    continue;
                }
                if(!bool){
                    log.info("excloud device:{}",device.getName());
                    continue;
                }

                //log.info("deviceName:{},ip:{}, is ipv4:{}",device.getName(),ip ,ipv4);
                Map<String, Set<String>> filterMap = DestInfo.build();
                String redirectUrl = "";
                CaptureThread captureThread = new CaptureThread(device, redirectUrl, filterMap);
                ThreadPool.getInstance().execute(captureThread);
            }
        } catch (Exception e) {
            log.error("启动抓取网卡服务异常：", e);
        }

    }

    @Override
    public void stop() {
        log.info("停止服务..");
    }

    @Override
    public int getOrder() {
        return 10;
    }

}
