package jp.agentec.abook.abv.bl.data.dao;

import jp.agentec.abook.abv.bl.common.db.SQLiteDatabase;
import jp.agentec.abook.abv.bl.common.db.SQLiteStatement;

public class ContentGroupDao extends AbstractDao {

	/*package*/ ContentGroupDao() {
	}

	public boolean insertContentGroup(int groupId, long contentId) {
		StringBuffer sql = new StringBuffer();

		sql.append(" INSERT OR IGNORE INTO r_content_group ");
		sql.append(" SELECT " + contentId);
		sql.append("      , mg.group_relation_id ");
		sql.append("   FROM m_group AS mg ");
		sql.append("   LEFT OUTER JOIN r_content_group AS rcg ");
		sql.append("     ON rcg.content_id = ? ");
		sql.append("    AND mg.group_relation_id <> rcg.group_relation_id ");
		sql.append("  WHERE mg.group_id = ? ");
		sql.append("  GROUP BY mg.group_relation_id ");

		SQLiteStatement stmt = null;

		try {
			SQLiteDatabase db = getDatabase();
			stmt = db.compileStatement(sql.toString());
			stmt.bindLong(1, contentId);
			stmt.bindLong(2, groupId);

			return (stmt.executeInsert() > 0);
		} finally {
			if (stmt != null) {
				stmt.close();
			}
		}
	}


	public void deleteContentGroup(long contentId) {
		delete("r_content_group", "content_id=?", new String[]{""+ contentId});
	}
}
