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.socket.NettyServerPermeateServerConnectVisitorSocket;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyInternalNetworkServerPermeateServerMappingApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.assembler.LazyInternalNetworkServerPermeateServerMappingDTOAssembler;
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.LazyInternalNetworkServerPermeateMappingDTO;
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 LazyInternalNetworkServerPermeateServerMappingApplicationImpl implements LazyInternalNetworkServerPermeateServerMappingApplication {

    @Resource
    LazyNettyServerPermeateServerMappingRepository lazyNettyServerPermeateServerMappingRepository;

    @Resource
    ServerNodeProperties serverNodeProperties;

    @Resource
    ChannelFlowAdapter channelFlowAdapter;

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

    @Override
    public Result<LazyNettyServerPermeateServerMapping> story(LazyInternalNetworkServerPermeateServerMappingStoryCommand lazyInternalNetworkServerPermeateServerMappingStoryCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingStoryCommand);
        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 lazyInternalNetworkServerPermeateServerMappingStoryCommandList 批量新增服务端网络渗透映射
     * @return {@link Result<List<  LazyNettyServerPermeateServerMapping  >>} 服务端网络渗透映射新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<List<LazyNettyServerPermeateServerMapping>> batchStory(List<LazyInternalNetworkServerPermeateServerMappingStoryCommand> lazyInternalNetworkServerPermeateServerMappingStoryCommandList) {
        List<LazyNettyServerPermeateServerMapping> lazyNettyServerPermeateServerMappingList = lazyInternalNetworkServerPermeateServerMappingStoryCommandList.stream().map(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.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 lazyInternalNetworkServerPermeateServerMappingUpdateCommand 更新服务端网络渗透映射
     * @return {@link Result<  LazyNettyServerPermeateServerMapping  >} 服务端网络渗透映射领域对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyNettyServerPermeateServerMapping> updateOne(LazyInternalNetworkServerPermeateServerMappingUpdateCommand lazyInternalNetworkServerPermeateServerMappingUpdateCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingUpdateCommand);
        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 lazyInternalNetworkServerPermeateServerMappingQueryOneCommand 查询单个服务端网络渗透映射
     * @return {@link Result<LazyInternalNetworkServerPermeateMappingDTO>} 服务端网络渗透映射DTO对象
     * @author Jia wei Wu
     * @date 2024/09/17 01:35 下午
     **/

    @Override
    public Result<LazyInternalNetworkServerPermeateMappingDTO> findOne(LazyInternalNetworkServerPermeateServerMappingQueryOneCommand lazyInternalNetworkServerPermeateServerMappingQueryOneCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingQueryOneCommand);
        return lazyNettyServerPermeateServerMappingRepository.findOne(lazyNettyServerPermeateServerMapping).convert(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping);
    }

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

    @Override
    public Result<List<LazyInternalNetworkServerPermeateMappingDTO>> findList(LazyInternalNetworkServerPermeateServerMappingQueryListCommand lazyInternalNetworkServerPermeateServerMappingQueryListCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingQueryListCommand);
        return lazyNettyServerPermeateServerMappingRepository.findList(lazyNettyServerPermeateServerMapping).convert(lazyInternalNetworkServerPermeateMappings -> lazyInternalNetworkServerPermeateMappings.stream().map(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping).collect(Collectors.toList()));
    }

    /**
     * describe 分页查询多个服务端网络渗透映射
     *
     * @param lazyInternalNetworkServerPermeateServerMappingQueryListCommand 分页查询多个服务端网络渗透映射
     * @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, LazyInternalNetworkServerPermeateServerMappingQueryListCommand lazyInternalNetworkServerPermeateServerMappingQueryListCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingQueryListCommand);
        return lazyNettyServerPermeateServerMappingRepository.findPage(size, current, lazyNettyServerPermeateServerMapping).convert(page -> page.convert(LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE::fromLazyInternalNetworkServerPermeateMapping));
    }

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

    @Override
    public Result<LazyNettyServerPermeateServerMapping> remove(LazyInternalNetworkServerPermeateServerMappingRemoveCommand lazyInternalNetworkServerPermeateServerMappingRemoveCommand) {
        LazyNettyServerPermeateServerMapping lazyNettyServerPermeateServerMapping = LazyInternalNetworkServerPermeateServerMappingDTOAssembler.INSTANCE.toLazyInternalNetworkServerPermeateMapping(lazyInternalNetworkServerPermeateServerMappingRemoveCommand);
        // 开启端口
        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) {
        // 删除 客户端映射
        NettyServerPermeateServerConnectVisitorSocket nettyServerPermeateServerConnectVisitorSocket = NettyServerPermeateServerVisitorContext.getServerPermeateServerVisitorSocket(visitorPort);
        if (!ObjectUtils.isEmpty(nettyServerPermeateServerConnectVisitorSocket)) {
            // 关闭端口
            try {
                nettyServerPermeateServerConnectVisitorSocket.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) {
        // 更新 客户端映射
        NettyServerPermeateServerConnectVisitorSocket nettyServerPermeateServerConnectVisitorSocket = NettyServerPermeateServerConnectVisitorSocket.NettyPermeateVisitorSocketBuilder
                .builder()
                .builderClientTargetIp(permeateTargetIp)
                .builderClientTargetPort(permeateTargetPort)
                .builderVisitorPort(visitorPort)
                .builderIsSsl(isSsl)
                .builderChannelFlowAdapter(channelFlowAdapter)
                .build();
        try {
            nettyServerPermeateServerConnectVisitorSocket.start();
        } catch (Exception e) {
            log.error("内网渗透,网络端口:{},开放失败", visitorPort);
            throw new RuntimeException(e);
        }
    }

}