package cn.reghao.bnt.web.devops.builder.chain;

import cn.reghao.bnt.web.devops.builder.chain.impl.BuildChainResult;
import cn.reghao.jutil.jdk.exception.ExceptionUtil;
import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.jdk.web.result.ResultStatus;

import java.util.List;
import java.util.function.Supplier;

/**
 * @author reghao
 * @date 2022-05-06 15:58:42
 */
public class Bootstrap<K extends HandlerParam, V extends HandlerResult> implements Supplier<HandlerResult> {
    private Handler<K, V> first;
    private final K buildParam;
    private final V buildResult;

    public Bootstrap(List<Handler<K, V>> list, K buildParam, V buildResult) {
        init(list);
        this.buildParam = buildParam;
        this.buildResult = buildResult;
    }

    @Override
    public V get() {
        Result result;
        try {
            first.handle(buildParam, buildResult);
            result = Result.result(ResultStatus.SUCCESS);
        } catch (Exception e) {
            String errMsg;
            if (e instanceof NullPointerException) {
                errMsg = ExceptionUtil.stackTrace(e);
            } else {
                errMsg = e.getMessage();
            }

            if (errMsg.length() > 20_000) {
                errMsg = errMsg.substring(0, 20_000);
            }
            result = Result.result(ResultStatus.FAIL, errMsg);
        } finally {
            /*if (buildResult instanceof BuildChainResult) {
            }*/
        }

        BuildChainResult buildChainResult = (BuildChainResult) buildResult;
        buildChainResult.setResult(result);
        return buildResult;
    }

    /**
     * 初始化职责链
     *
     * @param
     * @return
     * @date 2023-03-10 09:42:59
     */
    private void init(List<Handler<K, V>> list) {
        if (list.isEmpty()) {
            return;
        }

        this.first = list.get(0);
        Handler<K, V> handler = first;
        for (int i = 1; i < list.size(); i++) {
            handler = handler.addNext(list.get(i));
        }
    }
}
