package cd.casic.module.execute.docker.callback;

import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @description: 自定义执行命令回调类，用于处理命令执行过程中的输出和错误信息。目前这里是直接输出，随取随用，后面改
 * @author: mianbin
 * @date: 2025/5/27 22:23
 * @version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
public class CommandExecCallback extends ResultCallback.Adapter<Frame> {

    private final String containerId;
    private StringBuffer buffer = new StringBuffer(1024);
    @Override
    public void onNext(Frame frame) {
        String output = new String(frame.getPayload(), StandardCharsets.UTF_8);
        switch (frame.getStreamType()) {
            case STDOUT:
                System.out.print(output);
                log.info("标准输出: {}", output.trim());
                break;
            case STDERR:
                System.err.print(output);
                log.error("错误输出: {}", output.trim());
                break;
            default:
                log.warn("未知流类型: {}", frame.getStreamType());
        }
        super.onNext(frame);
    }

    @Override
    public void onError(Throwable throwable) {
        log.error("执行命令时出错: {}", throwable.getMessage(), throwable);
        super.onError(throwable);
    }

    @Override
    public void onComplete() {
        log.info("命令执行完毕");
        super.onComplete();
    }

    @Override
    public void close() throws IOException {
        log.debug("回调已关闭");
        super.close();
    }
}
