/*
 * This file is part of the DistSim distributed simulation framework (client)
 * Copyright (C) 2007 Ulf Hermann
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package brn.distsim.client.data;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class GroupResultsFiles extends DbBackedEntries<GroupResultsFiles.File> {

	public final static String TABLE_NAME = "group_out_files";

	public class File extends DbBackedEntries.Entry {

		public File(String remotePath) {
			super(remotePath);
		}

		public void performDbInsert(int groupId) throws SQLException {
			id = groupId;
			statement.execute("INSERT INTO " + TABLE_NAME + " SET remotePath='"
					+ name + "', groupId='" + id + "';");
		}

		public void performDbDelete() throws SQLException {
			statement.execute("DELETE FROM " + TABLE_NAME + " WHERE groupId='"
					+ id + "' AND remotePath='" + name + "';");
		}

		public void performDbUpdate() throws SQLException {
			performDbInsert(id);
		}
	}

	public GroupResultsFiles(Connection definitions, int groupId) {
		super(definitions, groupId);
	}

	public GroupResultsFiles(GroupResultsFiles other) {
		super(other);
	}

	public GroupResultsFiles(Connection db, int id, ResultSet set)
			throws SQLException {
		super(db, id, set);
	}

	@Override
	public File getEmptyDependent() {
		return new File(null);
	}

	@Override
	public File getDependent(ResultSet data) throws SQLException {
		return new File(data.getString("remotePath"));
	}

	@Override
	public File getDependent(File other) {
		return new File(other.name);
	}

	@Override
	public void loadFromDb() throws SQLException {
		ResultSet params = statement.executeQuery("SELECT * FROM " + TABLE_NAME
				+ " WHERE groupId=" + id + ";");
		super.loadFromDb(params);
	}

	public void add(String name) {
		if (entries.containsKey(name))
			return;
		else {
			File file = new File(name);
			put(file);
		}
	}

	public static List<String> getNames(Connection db, int studyId)
			throws SQLException {
		ResultSet names = db
				.createStatement()
				.executeQuery(
						"SELECT DISTINCT remotePath FROM "
								+ TABLE_NAME
								+ " WHERE groupId in (SELECT id FROM groups WHERE studyId="
								+ studyId + ");");
		return namesToList(names);
	}

}
