
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;

public class Modelo {
	private Connection connection;
	private static final String crearDB = "create database if not exists gestionGastos;\n";
	private static final String crearTranasccion = "create table if not exists transacciones (\n" + 
			"	id int primary key auto_increment,\n" + 
			"   nombre varchar(30),\n"+
			"	dinero float,\n" + 
			"   fecha date\n" + 
			");";
	
	Modelo(){
		try {
			connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/gestionGastos?user=root&password=1234");
			Statement crearDB = connection.createStatement();
			crearDB.executeQuery(Modelo.crearDB);
			crearDB.executeUpdate(Modelo.crearTranasccion);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void insertarTransaccion(String nombre, float dinero, String fecha) {
		 String query = "insert into transacciones(nombre, dinero, fecha) values(?, ?, ?);";
		 try {
			PreparedStatement stmt = this.connection.prepareStatement(query);
			stmt.setString(1, nombre);
			stmt.setFloat(2, dinero);
			stmt.setString(3, fecha);
			stmt.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ResultSet obtenerTransacciones() {
		String query = "select * " + 
				"from transacciones;";
		ResultSet ret = null; 
		try {
			PreparedStatement stmt = this.connection.prepareStatement(query);
			ret = stmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	public void eliminartransaccion(int id) {
		String query ="delete from transacciones " + 
				"where id=?;"; 
		try {
			PreparedStatement stmt = this.connection.prepareStatement(query);
			stmt.setInt(1, id);
			stmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void modificarTransaccion(int id, String nombre, float dinero, String fecha) {
		String query ="update transacciones " + 
				"set nombre=?, dinero=?, fecha=? "+
				"where id=?;";
		try {
			PreparedStatement stmt = this.connection.prepareStatement(query);
			stmt.setString(1, nombre);
			stmt.setFloat(2, dinero);
			stmt.setString(3, fecha);
			stmt.setInt(4, id);
			stmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ResultSet buscarTransaccion(int id) {
		String query = "select * " + 
				"from transacciones " + 
				"where id=?;";
		ResultSet ret = null; 
		try {
			PreparedStatement stmt = this.connection.prepareStatement(query);
			stmt.setInt(1, id);
			ret = stmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
}
