package cd.casic.framework.mongo.utils;

import cd.casic.framework.mongo.core.sdk.SFunction;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @author songqiang
 * @date 2023-08-01 11:21
 * @description 构造update
 */
public class UpdateBuilder<T> {

    private Update update;

    private UpdateBuilder() {

    }

    public static <T> UpdateBuilder<T> getInstance() {
        UpdateBuilder<T> builder = new UpdateBuilder<>();
        builder.setUpdate(new Update());
        return builder;
    }

    public UpdateBuilder<T> set(SFunction<T, ?> column, Object value) {
        this.update.set(getFieldMeta(column), value);
        return this;
    }

    public UpdateBuilder<T> incr(SFunction<T, ?> column, Number value) {
        this.update.inc(getFieldMeta(column), value);
        return this;
    }

    public UpdateBuilder<T> decr(SFunction<T, ?> column, Integer value) {
        this.update.inc(getFieldMeta(column), -value);
        return this;
    }

    private void setUpdate(Update update) {
        this.update = update;
    }

    public Update build() {
        return update;
    }

    private String getFieldMeta(SFunction<T, ?> column){
        return ConvertUtils.convertToFieldName(column);
    }
}
