package cn.axzo.msg.center.message.service.todo.manage;

import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.common.utils.PlaceholderResolver;
import cn.axzo.msg.center.domain.entity.Todo;
import cn.axzo.msg.center.message.domain.dto.MessageTemplateDTO;
import cn.axzo.msg.center.message.domain.param.PendingMessagePushParam;
import cn.axzo.msg.center.service.util.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;

import java.util.HashMap;

/**
 * @author yanglin
 */
@RequiredArgsConstructor
public class TodoExt {

    public static final String CTX = "ctx";

    private final PendingMessagePushParam request;
    private final MessageTemplateDTO template;

    private JSONObject bizExt;
    private JSONObject routerExt;
    private String title;
    private String content;

    JSONObject parseBizExtParams() {
        if (bizExt == null) {
            bizExt = JSONUtils.parseObjectOrThrow("bizExtParams", request.getBizExtParams());
            BizAssertions.assertFalse(bizExt.containsKey(CTX), "bizExtParams参数中不能包含键 {}", CTX);
        }
        return bizExt;
    }

    JSONObject parseRouterExtParams() {
        if (routerExt == null) {
            routerExt = JSONUtils.parseObjectOrThrow("routerParams", request.getRouterParams());
            BizAssertions.assertFalse(routerExt.containsKey(CTX), "routerParams参数中不能包含键 {}", CTX);
        }
        return routerExt;
    }

    public String parseTitle() {
        if (title == null) {
            JSONObject ext = (JSONObject)parseBizExtParams().clone();
            ext.put(CTX, ImmutableMap.of("request", request));
            title = PlaceholderResolver.tryResolve(template.getTitle(), ext);
        }
        return title;
    }

    public String parseContent() {
        if (content == null) {
            JSONObject ext = (JSONObject)parseBizExtParams().clone();
            ext.put(CTX, ImmutableMap.of("request", request));
            content = PlaceholderResolver.tryResolve(template.getContent(), ext);
        }
        return content;
    }

    public static JSONObject copyBizExtParam(Todo todo, boolean removeExt) {
        if (todo.getBizExtParam() == null)
            return null;
        JSONObject bizExtParam = new JSONObject(new HashMap<>(todo.getBizExtParam()));
        if (removeExt)
            bizExtParam.remove(TodoExt.CTX);
        return bizExtParam;
    }

    public static JSONObject copyRouterExtParam(Todo todo, boolean removeExt) {
        if (todo.getRouterParams() == null)
            return null;
        JSONObject routerExtParam = new JSONObject(new HashMap<>(todo.getRouterParams()));
        if (removeExt)
            routerExtParam.remove(TodoExt.CTX);
        return routerExtParam;
    }
}