package org.smartframework.mybatis.mapper.helper;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by chenweijiang on 2017/9/18.
 */
public class SqlHelper extends tk.mybatis.mapper.mapperhelper.SqlHelper {


    public static String updateSetColumns(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty, String[] properties) {
        StringBuilder sql = new StringBuilder();
        sql.append("<set>");
        Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
        if(properties != null && properties.length == 0){
            Set<EntityColumn> updateColumns = new HashSet<EntityColumn>();
            for(EntityColumn column : columnList){
                for(String property : properties){
                    if(column.getProperty().equals(property)){
                        updateColumns.add(column);
                        break;
                    }
                }
            }
            columnList = updateColumns;
        }
        Iterator iterator = columnList.iterator();
        while(iterator.hasNext()) {
            EntityColumn column = (EntityColumn)iterator.next();
            if(!column.isId() && column.isUpdatable()) {

                if(notNull) {
                    sql.append(getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty));
                } else {
                    sql.append(column.getColumnEqualsHolder(entityName) + ",");
                }
            }
        }

        sql.append("</set>");
        return sql.toString();
    }
}
