package bazy.podstawy;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Podwyzka2 {

	public static void main(String[] args) {
		final String url = "jdbc:postgresql://localhost/hr";
		final String sqlUpdate = "UPDATE employees SET salary = salary + ? WHERE job_id = ?";
		final String sqlAvg = "SELECT avg(salary) FROM employees WHERE job_id = ?";

		Scanner sc = new Scanner(System.in);
		System.out.print("Podaj job_id: ");
		String job = sc.nextLine();

		try(Connection c = DriverManager.getConnection(url, "kurs", "abc123")) {
			c.setAutoCommit(false);
			
			try(PreparedStatement stmtAvg = c.prepareStatement(sqlAvg)) {
				stmtAvg.setString(1, job);
				try(ResultSet rs = stmtAvg.executeQuery()) {
					if(rs.next()) {
						double srednia = rs.getDouble(1);
						System.out.printf("Średnia pensja: %.2f\n", srednia);
					}
				}
				System.out.print("Podaj kwotę podwyżki: ");
				BigDecimal kwota = sc.nextBigDecimal();
				
				try(PreparedStatement stmt = c.prepareStatement(sqlUpdate)) {
					stmt.setBigDecimal(1, kwota);
					stmt.setString(2, job);
					int ile = stmt.executeUpdate();
					System.out.println("Zmodyfikowano " + ile + " rekordów.");					
				}
				
				try(ResultSet rs = stmtAvg.executeQuery()) {
					if(rs.next()) {
						double srednia = rs.getDouble(1);
						System.out.printf("Średnia pensja: %.2f\n", srednia);
					}
				}
				
				System.out.print("Czy zatwierdzić transakcję? T / N: ");
				String wybor = sc.next().toUpperCase();
				switch(wybor) {
					case "T" -> c.commit();
					case "N" -> c.rollback();
				}
				try(ResultSet rs = stmtAvg.executeQuery()) {
					if(rs.next()) {
						double srednia = rs.getDouble(1);
						System.out.printf("Średnia pensja: %.2f\n", srednia);
					}
				}
				System.out.println("Koniec programu");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
