package cd.casic.module.terminal.host.terminal.handler;

import cd.casic.module.terminal.common.BooleanBit;
import cd.casic.module.terminal.common.OperatorLogs;
import cd.casic.module.terminal.dal.redis.TerminalRedisDAO;
import cd.casic.module.terminal.define.cache.TerminalCacheKeyDefine;
import cd.casic.module.terminal.define.operator.TerminalOperatorType;
import cd.casic.module.terminal.host.terminal.dto.SftpSetContentCacheDTO;
import cd.casic.module.terminal.host.terminal.enums.OutputTypeEnum;
import cd.casic.module.terminal.host.terminal.model.request.SftpBaseRequest;
import cd.casic.module.terminal.host.terminal.model.response.SftpSetContentResponse;
import cd.casic.module.terminal.host.terminal.session.ISftpSession;
import cn.orionsec.kit.lang.id.UUIds;
import cn.orionsec.kit.lang.utils.collect.Maps;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;

/**
 * sftp 设置文件内容
 *
 * @author Jiahang Li
 * @version 1.0.0
 * @since 2024/2/19 11:13
 */
@Slf4j
@Component
public class SftpSetContentHandler extends AbstractTerminalHandler<SftpBaseRequest> {

    @Resource
    private TerminalRedisDAO terminalRedisDAO;

    @Override
    public void handle(WebSocketSession channel, SftpBaseRequest payload) {
        long startTime = System.currentTimeMillis();
        // 获取会话
        String sessionId = payload.getSessionId();
        ISftpSession session = terminalManager.getSession(channel.getId(), sessionId);
        String path = payload.getPath();
        log.info("SftpSetContentHandler-handle start sessionId: {}, path: {}", sessionId, path);
        String token = UUIds.random32();
        Exception ex = null;
        try {
            // 检查文件是否可编辑
            session.checkCanEdit(path);
            // 设置缓存
            String key = TerminalCacheKeyDefine.TERMINAL_SFTP_SET_CONTENT.format(token);
            SftpSetContentCacheDTO cache = SftpSetContentCacheDTO.builder()
                    .hostId(session.getConfig().getHostId())
                    .path(path)
                    .build();
            terminalRedisDAO.setJson(key, TerminalCacheKeyDefine.TERMINAL_SFTP_SET_CONTENT, cache);
            log.info("SftpSetContentHandler-handle success sessionId: {}, path: {}", sessionId, path);
        } catch (Exception e) {
            log.error("SftpSetContentHandler-handle error sessionId: {}", sessionId, e);
            ex = e;
        }
        // 返回
        this.send(channel,
                OutputTypeEnum.SFTP_SET_CONTENT,
                SftpSetContentResponse.builder()
                        .sessionId(sessionId)
                        .result(BooleanBit.of(ex == null).getValue())
                        .token(token)
                        .msg(this.getErrorMessage(ex))
                        .build());
        // 保存操作日志
        Map<String, Object> extra = Maps.newMap();
        extra.put(OperatorLogs.PATH, path);
        this.saveOperatorLog(payload, channel,
                extra, TerminalOperatorType.SFTP_SET_CONTENT,
                startTime, ex);
    }

}
