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

import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.utils.UUIDUtil;
import com.alibaba.fastjson.JSON;
import lombok.Getter;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author yanglin
 */
@Getter
public class TodoRequestContext {
    private final String name;
    private final String requestNo;
    private final Map<String, Object> logContents = new LinkedHashMap<>();

    private TodoRequestContext(String name, String requestNo, Object request) {
        this.name = name;
        this.requestNo = requestNo;
        addLogContent("request", request);
    }

    private TodoRequestContext(String name, String requestNo) {
        this.name = name;
        this.requestNo = requestNo;
    }

    public static TodoRequestContext create(String name, Object request) {
        return new TodoRequestContext(name, UUIDUtil.uuidString(), request);
    }

    public static TodoRequestContext create(String name, String requestNo, Object request) {
        return new TodoRequestContext(name, requestNo, request);
    }

    public TodoRequestContext addLogContent(String name, Object... fields) {
        BizAssertions.assertNotNull(fields, "Fields can't be null");
        BizAssertions.assertTrue(fields.length % 2 == 0, "The length of fields must be an integer multiple of 2");
        Map<String, Object> fieldsObj = new HashMap<>();
        for (int i = 0; i < fields.length; i += 2)
            fieldsObj.put(String.valueOf(fields[i]), fields[i + 1]);
        addLogContent(name, fieldsObj);
        return this;
    }

    public TodoRequestContext addLogContent(String name, Object value) {
        if (name == null || value == null)
            return this;
        if (!logContents.containsKey(name))
            logContents.put(name, value);
        return this;
    }

    public TodoRequestContext copy() {
        TodoRequestContext copy = new TodoRequestContext(name, requestNo);
        copy.logContents.putAll(logContents);
        return copy;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}