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

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

import de.ugoe.cs.swe.exercises.lectureevent.LectureEvent;
import de.ugoe.cs.swe.exercises.misc.Model;

public class Lecture extends Model {
	private String name;

	@Override
	protected String getTableName() {
		return "lecture";
	}

	public Lecture(String name) {
		super();
		this.name = name;
	}

	public Lecture(int id, String name) {
		super(id);
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	protected void update() throws SQLException {
		PreparedStatement statement = Model
				.prepareStatement("UPDATE lecture SET name=? WHERE id=?");
		statement.setString(1, this.getName());
		statement.setInt(2, this.getId());
		statement.executeUpdate();
	}

	@Override
	protected PreparedStatement insert() throws SQLException {
		PreparedStatement statement = Model
				.prepareStatement("INSERT INTO lecture (name) VALUES (?)");
		statement.setString(1, this.getName());
		statement.executeUpdate();
		return statement;
	}

	public static ArrayList<Lecture> all() {
		try {
			return fromStatement(Model
					.prepareStatement("SELECT * FROM lecture"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static ArrayList<Lecture> fromStatement(PreparedStatement statement)
			throws SQLException {
		ResultSet resultset = statement.executeQuery();
		ArrayList<Lecture> lectures = new ArrayList<Lecture>();
		while (resultset.next()) {
			lectures.add(new Lecture(resultset.getInt("id"), resultset
					.getString("name")));
		}
		return lectures;
	}

	public static Lecture get(int lectureId) {
		try {
			PreparedStatement statement = prepareStatement("SELECT * FROM lecture WHERE id=?");
			statement.setInt(1, lectureId);
			return fromStatement(statement).get(0);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IndexOutOfBoundsException e) {
		}
		throw new Model.DoesNotExistException();
	}
	public ArrayList<LectureEvent> getLectureEvents () {
		try {
			PreparedStatement statement = prepareStatement("SELECT DISTINCT lectureevent.* FROM lecture, lectureevent WHERE lecture.id = ? AND lectureevent.lecture = lecture.id ORDER BY id");
			statement.setInt(1, this.getId());
			return LectureEvent.fromStatement(statement);
		} catch (SQLException e) {
			System.err
					.println("Got an exception in Lecture.getLectureEvents()! ");
			System.err.println(e.getMessage());
		}
		return null;
	}
}
