package com.lanyuanxiaoyao.service.executor.task.helper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.executor.core.TaskConstants;
import com.lanyuanxiaoyao.service.executor.core.TaskContext;
import java.util.Map;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;

/**
 * 入参解析相关内容
 *
 * @author ZhangJiacheng
 * @date 2022-03-10
 */
public class ArgumentsHelper {
    public static TaskContext getContext(String[] args) throws JsonProcessingException {
        ParameterTool argsTool = ParameterTool.fromArgs(args);
        if (!argsTool.has(TaskConstants.TASK_CONTEXT)) {
            throw new RuntimeException(StrUtil.format("Miss argument: {}", TaskConstants.TASK_CONTEXT));
        }
        return JacksonHelper.getMapper().readValue(argsTool.get(TaskConstants.TASK_CONTEXT), TaskContext.class);
    }

    public static void checkMetadata(TaskContext context, String key) {
        Map<String, Object> metadata = context.getMetadata();
        if (ObjectUtil.isEmpty(metadata)) {
            throw new RuntimeException("Metadata is empty");
        }
        if (!metadata.containsKey(key)) {
            throw new RuntimeException(key + " argument is not found");
        }
    }
}
