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

import cn.axzo.msg.center.utils.DateFormatUtil;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yanglin
 */
@Data
public class AnalyzeResult {

    private String warn;
    private List<FailMatch> failMatches = new ArrayList<>();

    void addFailMatch(FailMatch failMatch) {
        failMatches.add(failMatch);
    }

    @Getter
    public static class FailMatch {

        private final String executedQuery;
        private final String failReason;

        FailMatch(SQLObject expr, String column, Object actualValue) {
            Object value = actualValue;
            if (actualValue instanceof Date)
                value = DateFormatUtil.toReadableString((Date) actualValue);
            this.executedQuery = SQLUtils.toMySqlString(expr);
            this.failReason = String.format("%s = %s", column, value);
        }
    }

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