package dev.peerat.backend;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import dev.peerat.backend.repository.DatabaseRepository;

public class TestDatabaseRepository extends DatabaseRepository{

	private Connection con;
	private String schem;
	
	public TestDatabaseRepository(Configuration config, File databaseSchem){
		super(config);
		
		try{
			schem = "";
			BufferedReader reader = new BufferedReader(new FileReader(databaseSchem));
			String line;
			while((line = reader.readLine()) != null) schem+=line;
			reader.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void init(){
		try {
			Method method = DatabaseRepository.class.getDeclaredMethod("ensureConnection");
			method.setAccessible(true);
			method.invoke(this);
			
			Field field = DatabaseRepository.class.getDeclaredField("con");
			field.setAccessible(true);
			this.con = (Connection) field.get(this);
		}catch(Exception e){
			e.getCause().printStackTrace();
		}
	}
	
	public void close(){
		try {
			this.con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void reset(){
		try{
			String[] split = schem.split(";");
			for(String statment : split){
				this.con.prepareStatement(statment).execute();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
