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.NettyServerPermeateServerVisitorContext;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelFlowAdapter;
import org.framework.lazy.cloud.network.heartbeat.server.netty.tcp.socket.NettyTcpServerPermeateServerConnectVisitorSocket;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyServerPermeateServerMappingApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.assembler.LazyNettyServerPermeateServerMappingDTOAssembler;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.lazy.netty.server.permeate.server.mapping.*;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.dto.LazyServerPermeateServerMappingDTO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.permeate.server.mapping.LazyNettyServerPermeateServerMapping;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.server.permeate.server.mapping.LazyNettyServerPermeateServerMappingRepository;
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 LazyServerPermeateServerMappingApplicationImpl implements LazyServerPermeateServerMappingApplication {

    @Resource
    LazyNettyServerPermeateServerMappingRepository lazyNettyServerPermeateServerMappingRepository;

    @Resource
    ServerNodeProperties serverNodeProperties;

    @Resource
    ChannelFlowAdapter channelFlowAdapter;

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

    @Override
    public Result<LazyNettyServerPermeateServerMapping> story(LazyServerPermeateServerMappingStoryCommand lazyServerPermeateServerMappingStoryCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyServerPermeateServerMappingStoryCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyNettyServerPermeateServerMapping.setServerId(serverId);
        // 开启端口
        String permeateTargetIp = lazyNettyServerPermeateServerMapping.getPermeateTargetIp();
        Integer permeateTargetPort = lazyNettyServerPermeateServerMapping.getPermeateTargetPort();
        Integer visitorPort = lazyNettyServerPermeateServerMapping.getVisitorPort();
        Boolean isSsl = lazyNettyServerPermeateServerMapping.getIsSsl();
        this.changeServerPermeateServerSocket(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
        return lazyNettyServerPermeateServerMappingRepository.story(lazyNettyServerPermeateServerMapping);
    }

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

    @Override
    public Result<List<LazyNettyServerPermeateServerMapping>> batchStory(List<LazyServerPermeateServerMappingStoryCommand> lazyServerPermeateServerMappingStoryCommandList) {
        List<LazyNettyServerPermeateServerMapping> lazyNettyServerPermeateServerMappingList = lazyServerPermeateServerMappingStoryCommandList.stream().map(LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE::toLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList());
        for (LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping : lazyNettyServerPermeateServerMappingList) {
            String serverId = serverNodeProperties.getNodeId();
            lazyNettyServerPermeateServerMapping.setServerId(serverId);
            // 开启端口
            String permeateTargetIp = lazyNettyServerPermeateServerMapping.getPermeateTargetIp();
            Integer permeateTargetPort = lazyNettyServerPermeateServerMapping.getPermeateTargetPort();
            Integer visitorPort = lazyNettyServerPermeateServerMapping.getVisitorPort();
            Boolean isSsl = lazyNettyServerPermeateServerMapping.getIsSsl();
            this.changeServerPermeateServerSocket(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
        }
        return lazyNettyServerPermeateServerMappingRepository.batchStory(lazyNettyServerPermeateServerMappingList);
    }

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

    @Override
    public Result<LazyNettyServerPermeateServerMapping> updateOne(LazyServerPermeateServerMappingUpdateCommand lazyServerPermeateServerMappingUpdateCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyServerPermeateServerMappingUpdateCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyNettyServerPermeateServerMapping.setServerId(serverId);
        // 开启端口
        String permeateTargetIp = lazyNettyServerPermeateServerMapping.getPermeateTargetIp();
        Integer permeateTargetPort = lazyNettyServerPermeateServerMapping.getPermeateTargetPort();
        Integer visitorPort = lazyNettyServerPermeateServerMapping.getVisitorPort();
        Boolean isSsl = lazyNettyServerPermeateServerMapping.getIsSsl();
        this.changeServerPermeateServerSocket(permeateTargetIp, permeateTargetPort, visitorPort,isSsl);
        return lazyNettyServerPermeateServerMappingRepository.story(lazyNettyServerPermeateServerMapping);
    }

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

    @Override
    public Result<LazyServerPermeateServerMappingDTO> findOne(LazyServerPermeateServerMappingQueryOneCommand lazyServerPermeateServerMappingQueryOneCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyServerPermeateServerMappingQueryOneCommand);
        return lazyNettyServerPermeateServerMappingRepository.findOne(lazyNettyServerPermeateServerMapping).convert(LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping);
    }

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

    @Override
    public Result<List<LazyServerPermeateServerMappingDTO>> findList(LazyServerPermeateServerMappingQueryListCommand lazyServerPermeateServerMappingQueryListCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyServerPermeateServerMappingQueryListCommand);
        return lazyNettyServerPermeateServerMappingRepository.findList(lazyNettyServerPermeateServerMapping).convert(lazyInternalNetworkServerPermeateMappings -> lazyInternalNetworkServerPermeateMappings.stream().map(LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList()));
    }

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

    @Override
    public Result<LazyPage<LazyServerPermeateServerMappingDTO>> findPage(int size, int current, LazyServerPermeateServerMappingQueryListCommand lazyServerPermeateServerMappingQueryListCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyServerPermeateServerMappingQueryListCommand);
        return lazyNettyServerPermeateServerMappingRepository.findPage(size, current, lazyNettyServerPermeateServerMapping).convert(page -> page.convert(LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping));
    }

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

    @Override
    public Result<LazyNettyServerPermeateServerMapping> remove(LazyServerPermeateServerMappingRemoveCommand lazyServerPermeateServerMappingRemoveCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyNettyServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyServerPermeateServerMappingRemoveCommand);
        // 开启端口
        Integer visitorPort = lazyNettyServerPermeateServerMapping.getVisitorPort();
        this.closeServerPermeateServerSocket(visitorPort);
        return lazyNettyServerPermeateServerMappingRepository.remove(lazyNettyServerPermeateServerMapping);
    }

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

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

    }

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


    /**
     * 删除 通道
     *
     * @param visitorPort 访客端口
     */
    private void closeServerPermeateServerSocket(Integer visitorPort) {
        // 删除 客户端映射
        NettyTcpServerPermeateServerConnectVisitorSocket nettyTcpServerPermeateServerConnectVisitorSocket = NettyServerPermeateServerVisitorContext.getServerPermeateServerVisitorSocket(visitorPort);
        if (!ObjectUtils.isEmpty(nettyTcpServerPermeateServerConnectVisitorSocket)) {
            // 关闭端口
            try {
                nettyTcpServerPermeateServerConnectVisitorSocket.close();
                NettyServerPermeateServerVisitorContext.removeServerPermeateServerVisitorSockets(visitorPort);
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

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

}