package org.framework.lazy.cloud.network.heartbeat.server.standalone.application.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyPermeateVisitorContext;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelFlowAdapter;
import org.framework.lazy.cloud.network.heartbeat.server.netty.socket.NettyServerPermeateServerConnectVisitorSocket;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyInternalNetworkServerPermeateMappingApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.assembler.LazyInternalNetworkServerPermeateMappingDTOAssembler;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.lazy.internal.network.server.permeate.mapping.*;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.dto.LazyInternalNetworkServerPermeateMappingDTO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.internal.network.server.permeate.mapping.LazyInternalNetworkServerPermeateMapping;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.internal.network.server.permeate.mapping.LazyInternalNetworkServerPermeateMappingRepository;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.database.lazy.web.plus.stereotype.LazyApplication;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.web.response.Result;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe 服务端网络渗透映射
 *
 * @author Jia wei Wu
 * @date 2024/09/17 01:35 下午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyApplicationImpl
 **/
@Slf4j
@LazyApplication
public class LazyInternalNetworkServerPermeateMappingApplicationImpl implements LazyInternalNetworkServerPermeateMappingApplication {

    @Resource
    LazyInternalNetworkServerPermeateMappingRepository lazyInternalNetworkServerPermeateMappingRepository;

    @Resource
    ServerNodeProperties serverNodeProperties;

    @Resource
    ChannelFlowAdapter channelFlowAdapter;

    /**
     * describe 新增服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingStoryCommand 新增服务端网络渗透映射
     * @return {@link Result<LazyInternalNetworkServerPermeateMapping>} 服务端网络渗透映射新增后领域对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateMapping> story(LazyInternalNetworkServerPermeateMappingStoryCommand lazyInternalNetworkServerPermeateMappingStoryCommand) {
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateMappingStoryCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyInternalNetworkServerPermeateMapping.setServerId(serverId);
        // 开启端口
        String permeateTargetIp = lazyInternalNetworkServerPermeateMapping.getPermeateTargetIp();
        Integer permeateTargetPort = lazyInternalNetworkServerPermeateMapping.getPermeateTargetPort();
        Integer visitorPort = lazyInternalNetworkServerPermeateMapping.getVisitorPort();
        this.changePermeateSocket(permeateTargetIp, permeateTargetPort, visitorPort);
        return lazyInternalNetworkServerPermeateMappingRepository.story(lazyInternalNetworkServerPermeateMapping);
    }

    /**
     * describe 批量新增服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingStoryCommandList 批量新增服务端网络渗透映射
     * @return {@link Result<List<LazyInternalNetworkServerPermeateMapping>>} 服务端网络渗透映射新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<List<LazyInternalNetworkServerPermeateMapping>> batchStory(List<LazyInternalNetworkServerPermeateMappingStoryCommand> lazyInternalNetworkServerPermeateMappingStoryCommandList) {
        List<LazyInternalNetworkServerPermeateMapping> lazyInternalNetworkServerPermeateMappingList = lazyInternalNetworkServerPermeateMappingStoryCommandList.stream().map(LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE::toLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList());
        for (LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping : lazyInternalNetworkServerPermeateMappingList) {
            String serverId = serverNodeProperties.getNodeId();
            lazyInternalNetworkServerPermeateMapping.setServerId(serverId);
            // 开启端口
            String permeateTargetIp = lazyInternalNetworkServerPermeateMapping.getPermeateTargetIp();
            Integer permeateTargetPort = lazyInternalNetworkServerPermeateMapping.getPermeateTargetPort();
            Integer visitorPort = lazyInternalNetworkServerPermeateMapping.getVisitorPort();
            this.changePermeateSocket(permeateTargetIp, permeateTargetPort, visitorPort);
        }
        return lazyInternalNetworkServerPermeateMappingRepository.batchStory(lazyInternalNetworkServerPermeateMappingList);
    }

    /**
     * describe 更新服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingUpdateCommand 更新服务端网络渗透映射
     * @return {@link Result<LazyInternalNetworkServerPermeateMapping>} 服务端网络渗透映射领域对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateMapping> updateOne(LazyInternalNetworkServerPermeateMappingUpdateCommand lazyInternalNetworkServerPermeateMappingUpdateCommand) {
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateMappingUpdateCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyInternalNetworkServerPermeateMapping.setServerId(serverId);
        // 开启端口
        String permeateTargetIp = lazyInternalNetworkServerPermeateMapping.getPermeateTargetIp();
        Integer permeateTargetPort = lazyInternalNetworkServerPermeateMapping.getPermeateTargetPort();
        Integer visitorPort = lazyInternalNetworkServerPermeateMapping.getVisitorPort();
        this.changePermeateSocket(permeateTargetIp, permeateTargetPort, visitorPort);
        return lazyInternalNetworkServerPermeateMappingRepository.story(lazyInternalNetworkServerPermeateMapping);
    }

    /**
     * describe 查询单个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingQueryOneCommand 查询单个服务端网络渗透映射
     * @return {@link Result<LazyInternalNetworkServerPermeateMappingDTO>} 服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateMappingDTO> findOne(LazyInternalNetworkServerPermeateMappingQueryOneCommand lazyInternalNetworkServerPermeateMappingQueryOneCommand) {
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateMappingQueryOneCommand);
        return lazyInternalNetworkServerPermeateMappingRepository.findOne(lazyInternalNetworkServerPermeateMapping).convert(LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping);
    }

    /**
     * describe 查询多个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingQueryListCommand 查询多个服务端网络渗透映射
     * @return {@link Result<List<LazyInternalNetworkServerPermeateMappingDTO>>} 服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<List<LazyInternalNetworkServerPermeateMappingDTO>> findList(LazyInternalNetworkServerPermeateMappingQueryListCommand lazyInternalNetworkServerPermeateMappingQueryListCommand) {
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateMappingQueryListCommand);
        return lazyInternalNetworkServerPermeateMappingRepository.findList(lazyInternalNetworkServerPermeateMapping).convert(lazyInternalNetworkServerPermeateMappings -> lazyInternalNetworkServerPermeateMappings.stream().map(LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList()));
    }

    /**
     * describe 分页查询多个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingQueryListCommand 分页查询多个服务端网络渗透映射
     * @return {@link Result<LazyPage<LazyInternalNetworkServerPermeateMappingDTO>>} 分页服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyPage<LazyInternalNetworkServerPermeateMappingDTO>> findPage(int size, int current, LazyInternalNetworkServerPermeateMappingQueryListCommand lazyInternalNetworkServerPermeateMappingQueryListCommand) {
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateMappingQueryListCommand);
        return lazyInternalNetworkServerPermeateMappingRepository.findPage(size, current, lazyInternalNetworkServerPermeateMapping).convert(page -> page.convert(LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping));
    }

    /**
     * describe 删除服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateMappingRemoveCommand 删除服务端网络渗透映射
     * @return {@link Result<LazyInternalNetworkServerPermeateMapping>} 服务端网络渗透映射
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateMapping> remove(LazyInternalNetworkServerPermeateMappingRemoveCommand lazyInternalNetworkServerPermeateMappingRemoveCommand) {
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = LazyInternalNetworkServerPermeateMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateMappingRemoveCommand);
        // 开启端口
        Integer visitorPort = lazyInternalNetworkServerPermeateMapping.getVisitorPort();
        this.closePermeateSocket(visitorPort);
        return lazyInternalNetworkServerPermeateMappingRepository.remove(lazyInternalNetworkServerPermeateMapping);
    }

    /**
     * 初始化 网络渗透socket
     *
     * @return
     */
    @Override
    public Result<?> initPermeateSocket() {
        // 查询所有的服务端渗透配置
        LazyInternalNetworkServerPermeateMapping lazyInternalNetworkServerPermeateMapping = new LazyInternalNetworkServerPermeateMapping();
        return lazyInternalNetworkServerPermeateMappingRepository.findList(lazyInternalNetworkServerPermeateMapping)
                .accept(lazyInternalNetworkServerPermeateMappings -> {
                    // 开启映射
                    for (LazyInternalNetworkServerPermeateMapping internalNetworkServerPermeateMapping : lazyInternalNetworkServerPermeateMappings) {

                        String permeateTargetIp = internalNetworkServerPermeateMapping.getPermeateTargetIp();
                        Integer permeateTargetPort = internalNetworkServerPermeateMapping.getPermeateTargetPort();
                        Integer visitorPort = internalNetworkServerPermeateMapping.getVisitorPort();
                        log.info("init permeate socket ip:{}, port:{},visitorPort:{}", permeateTargetIp, permeateTargetPort, visitorPort);
                        this.createPermeateVisitor(permeateTargetIp, permeateTargetPort, visitorPort);
                    }
                });

    }

    /**
     * 变更 网络穿透
     *
     * @param permeateTargetIp   客户端目标IP
     * @param permeateTargetPort 客户端莫表端口
     * @param visitorPort        访客端口
     */
    private void changePermeateSocket(String permeateTargetIp, Integer permeateTargetPort, Integer visitorPort) {
        // 删除 客户端映射
        this.closePermeateSocket(visitorPort);
        // 更新 客户端映射
        createPermeateVisitor(permeateTargetIp, permeateTargetPort, visitorPort);
    }


    /**
     * 删除 通道
     *
     * @param visitorPort 访客端口
     */
    private void closePermeateSocket(Integer visitorPort) {
        // 删除 客户端映射
        NettyServerPermeateServerConnectVisitorSocket nettyServerPermeateServerConnectVisitorSocket = NettyPermeateVisitorContext.getPermeateVisitorSocket(visitorPort);
        if (!ObjectUtils.isEmpty(nettyServerPermeateServerConnectVisitorSocket)) {
            // 关闭端口
            try {
                nettyServerPermeateServerConnectVisitorSocket.close();
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 创建访客
     *
     * @param permeateTargetIp   客户端目标IP
     * @param permeateTargetPort 客户端目标端口
     * @param visitorPort        访客端口
     */
    private void createPermeateVisitor(String permeateTargetIp, Integer permeateTargetPort, Integer visitorPort) {
        // 更新 客户端映射
        NettyServerPermeateServerConnectVisitorSocket nettyServerPermeateServerConnectVisitorSocket = NettyServerPermeateServerConnectVisitorSocket.NettyPermeateVisitorSocketBuilder
                .builder()
                .builderClientTargetIp(permeateTargetIp)
                .builderClientTargetPort(permeateTargetPort)
                .builderVisitorPort(visitorPort)
                .builderChannelFlowAdapter(channelFlowAdapter)
                .build();
        try {
            nettyServerPermeateServerConnectVisitorSocket.start();
        } catch (Exception e) {
            log.error("内网渗透,网络端口:{},开放失败", visitorPort);
            throw new RuntimeException(e);
        }
    }

}