package de.ugoe.cs.swe.exercises.misc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class CKeyword {
	
	public final static int LECTURE=0;
	public final static int EXERCISE=1;
	public final static int EXERCISESHEET=2;
	
	private final static String[] TABLE_NAMES = { "lecture", "exercise", "exercisesheet" };
	private final static String[] FIELD_NAMES =  { "lecture", "exercise", "exercisesheet" };
	
	private int keyId;
	private String key;
	private int modelId; // example lectureId

	public CKeyword(String key, int modelId) {
		this.keyId = Model.UNDEFINED;
		this.key = key;
		this.modelId = modelId;
	}

	public CKeyword(int keyId, String key, int modelId) {
		this.keyId = keyId;
		this.key = key;
		this.modelId = modelId;
	}

	public String getKey() {
		return key;
	}

	public int getKeyId() {
		return keyId;
	}

	public int getModelId() {
		return modelId;
	}
	
	public static ArrayList<CKeyword> fromKeyStatement(
			PreparedStatement statement, int modelType) throws SQLException {
		ResultSet resultset = statement.executeQuery();
		ArrayList<CKeyword> keys = new ArrayList<CKeyword>();
		while (resultset.next()) {
			keys.add(new CKeyword(resultset.getInt("id"), resultset
					.getString("word"), resultset.getInt(FIELD_NAMES[modelType])));
		}
		return keys;
	}

	public static ArrayList<CKeyword> getKeywordsForModel(int modelId, int modelType) {
		if(modelId < 0) {
			modelId = 0;
		}
		try {
			PreparedStatement statement = Model
					.prepareStatement("SELECT * FROM keyword_" + CKeyword.TABLE_NAMES[modelType] + " WHERE " + CKeyword.FIELD_NAMES[modelType] + "=?");
			statement.setInt(1, modelId);
			return fromKeyStatement(statement, modelType);
		} catch (SQLException e) {
			System.err
					.println("Got an exception in Lecture.getKeywordsForModel()! ");
			System.err.println(e.getMessage());
		} catch (IndexOutOfBoundsException e) {
		}
		//throw new Model.DoesNotExistException();
		return null;
	}

	public static void insertKey(CKeyword key, int modelType) {
		try {
			PreparedStatement statement = Model
					.prepareStatement("INSERT INTO keyword_" + CKeyword.TABLE_NAMES[modelType] + " (word," + CKeyword.FIELD_NAMES[modelType] + ") VALUES (?,?)");
			statement.setString(1, key.getKey());
			statement.setInt(2, key.getModelId());
			statement.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}

	public static void deleteKey(int id, int modelType) {
		try {
			PreparedStatement statement = Model.prepareStatement("DELETE FROM keyword_" + CKeyword.TABLE_NAMES[modelType] + " WHERE id=?");
			statement.setInt(1, id);
			statement.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}
}
