package cn.stylefeng.team.meta.db.querybuilder;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.team.meta.db.pojo.query.FilterItem;
import cn.stylefeng.team.meta.db.pojo.query.Group;
import cn.stylefeng.team.meta.db.util.QueryConditionUtil;

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

public class QueryConditionBuilder {

    public String build(Group group) {

        if (group == null || ObjectUtil.isEmpty(group.getFilters())) {
            return "";
        }

        List<String> parts = new ArrayList<>();

        List<FilterItem> filters = group.getFilters();
        for (FilterItem filter : filters) {


            if (filter.getField() != null) {
                parts.add(filter.getField() + " " + filter.getOperator() + " " + QueryConditionUtil.escapeValue(filter.getValue()));
                parts.add(" " + filter.getLogic() + " ");
            }

            if (filter.getGroup() != null && filter.getGroupLogic() != null) {
                parts.add(" ( ");
                parts.add(build(filter.getGroup()));
                parts.add(" ) ");
                parts.add(" " + filter.getGroupLogic() + " ");
            }
        }

        String result = String.join(" ", parts);

        result = QueryConditionUtil.removeEndingAndOr(result);

        return result;
    }

}