package common.utils.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

import java.util.concurrent.atomic.AtomicInteger;

public class SaveUtil {
	public static final int SAVE_CODE = 1;
	public static final int UPDATE_CODE = 2;
	
	public static int saveOrUpdate(Model<?> model) {
		Object[] values = CopyUtil.generateDuplicateObjects(model._getAttrValues());
		
		return Db.update(SqlUtil.generateReplaceSql(TableUtil.getTableName(model), model), values);
	}
	
	public static int saveSuperAndSub(Model<?> superModel, Model<?> subModel) {
		AtomicInteger code = new AtomicInteger();

		Db.tx(() -> {
			SaveUtil.saveOrUpdate(superModel);

			code.set(SaveUtil.saveOrUpdate(subModel));

			return true;
		});

		return code.get();
	}
}
