package agenda;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.sql.Statement;

public class Database {
  //db connection
  private Connection connect = null;
  //preparedstatement for filling db with acts
  private PreparedStatement preparedStatement = null;
  //statement for checking if db already has stages stored
  private Statement statement = null;
  
  //database values
  private String host = "jdbc:mysql://jancokock.me:3306/festivalagenda";
  private String user = "projectgroepa6";
  private String pass = "tzHnYRbpt7r3z4jt";
  
  //get agenda values
  private Agenda agenda;
  private ArrayList<Act> acts;

  public Database(Agenda agenda){
	  this.agenda = agenda;
	  acts = (ArrayList<Act>) agenda.getActs();
  }
  
  public void writeDatabase() throws Exception {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      connect = DriverManager.getConnection(host,user,pass);

      //First delete all act records in DB and set auto increment back to 1
      statement = connect.createStatement();
      statement.executeUpdate("delete from festivalagenda.acts");
      statement.executeUpdate("ALTER TABLE festivalagenda.acts AUTO_INCREMENT = 1");
	  
      //insert stage names
      
      for(Act act : acts){
    	  String stage = act.getStage().getName();
    	  String name = act.getName();
    	  String genre = act.getGenre();
    	  String beginTime = act.getActTime().getBeginTimeString();
    	  String endTime = act.getActTime().getEndTimeString();
    	  int popularity = act.getPopularity();

    	  //insert act data into database
    	  preparedStatement = connect.prepareStatement("insert into  festivalagenda.acts (stage, begintijd, eindtijd, naam, genre, populariteit) values (?, ?, ?, ?, ?, ?)");
    	  preparedStatement.setString(1, stage);
    	  preparedStatement.setString(2, beginTime);
    	  preparedStatement.setString(3, endTime);
          preparedStatement.setString(4, name);
          preparedStatement.setString(5, genre);
          preparedStatement.setInt(6, popularity);
          preparedStatement.executeUpdate();
          
      }
            
    } catch (Exception e) {
      throw e;
    } finally {
    	if (preparedStatement != null) {
            preparedStatement.close();
          }

          if (connect != null) {
            connect.close();
          }
    }

  }
} 