package me.chyxion.tigon.mybatis;

import org.w3c.dom.Element;
import org.w3c.dom.Document;
import me.chyxion.tigon.model.BaseModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Feb 21, 2017 17:41:26
 */
public class InsertXmlProcessor extends AbstractOnMissingCreateProcessor {

    /**
     * {@inheritDoc}
     */
    @Override
    protected String missingXPathExpression() {
        return "/mapper/insert[@id='insert']";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Element elementToAppend(Class<BaseMapper<?, ?>> mapperClass, Document doc) {
        final Element insertEl = doc.createElement("insert");
        insertEl.setAttribute("id", "insert");
        Class<BaseModel<?>> modelClass = getModelClass(mapperClass);
        UseGeneratedKeys ugkAnnotation =
            AnnotationUtils.findAnnotation(modelClass, UseGeneratedKeys.class);
        if (ugkAnnotation != null) {
            insertEl.setAttribute("useGeneratedKeys", "true");
            String keyProp = ugkAnnotation.value();
            if (StringUtils.isNotBlank(keyProp)) {
                insertEl.setAttribute("keyProperty", keyProp);
            }
        }
        return appendIncludeEl(doc, insertEl, "Tigon.insert");
    }
}
