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

import cn.axzo.msg.center.dal.TodoDao;
import cn.axzo.msg.center.domain.entity.Todo;
import cn.axzo.msg.center.service.enums.PendingMessageStateEnum;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import lombok.Getter;

import java.util.stream.Stream;

/**
 * @author yanglin
 */
@Getter
class StateAdvanceBuilder {

    private final LambdaQueryChainWrapper<Todo> query;
    private final LambdaQueryChainWrapper<Todo> noStateQuery;
    private final LambdaUpdateChainWrapper<Todo> update;

    StateAdvanceBuilder(TodoDao todoDao) {
        this.query = todoDao.lambdaQuery();
        this.noStateQuery = todoDao.lambdaQuery();
        this.update = todoDao.lambdaUpdate();
    }

    StateAdvanceBuilder eq(SFunction<Todo, ?> column, Object val) {
        query.eq(column, val);
        update.eq(column, val);
        if (!(val instanceof PendingMessageStateEnum))
            noStateQuery.eq(column, val);
        return this;
    }

    StateAdvanceBuilder eq(boolean condition, SFunction<Todo, ?> column, Object val) {
        query.eq(condition, column, val);
        update.eq(condition, column, val);
        if (!(val instanceof PendingMessageStateEnum))
            noStateQuery.eq(condition, column, val);
        return this;
    }

    StateAdvanceBuilder in(SFunction<Todo, ?> column, Object... values) {
        query.in(column, values);
        update.in(column, values);
        boolean statePresent = Stream.of(values).anyMatch(v -> v instanceof PendingMessageStateEnum);
        if (!statePresent)
            noStateQuery.in(column, values);
        return this;
    }

    StateAdvanceBuilder in(boolean condition, SFunction<Todo, ?> column, Object... values) {
        query.in(condition, column, values);
        update.in(condition, column, values);
        boolean statePresent = Stream.of(values).anyMatch(v -> v instanceof PendingMessageStateEnum);
        if (!statePresent)
            noStateQuery.in(condition, column, values);
        return this;
    }

    StateAdvanceBuilder set(SFunction<Todo, ?> column, Object val) {
        update.set(column, val);
        return this;
    }

}