package me.chyxion.tigon.mybatis;

import java.util.Collection;

/**
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * 2017/1/23 16:57
 */
abstract class AbstractSearchProcessor implements SearchProcessor {

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean accept(SearchProcessArgs args) {
        return args.getCriterion().getType().equals(type());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void process(SearchProcessArgs args) {
        if (args.isHasPrevOrCol()) {
            args.append(" or ");
            args.setHasPrevOrCol(false);
        }
        else if (args.isHasPrevCol()) {
            args.append(" and ");
        }
        doProcess(args);
    }

    abstract void doProcess(SearchProcessArgs args);

    abstract CriterionType type();

    void processInList(SearchProcessArgs args, boolean in) {
        args.append(args.getCol() +
            (in ? " in (" : " not in ("));
        Collection<?> values = args.getCriterion().getValues();
        int valuesSize = values.size();
        int i = 0;
        for (Object value : values) {
            args.addValue(value);
            if (++i < valuesSize) {
                args.append(", ");
            }
        }
        args.append(")");
    }
}
