package dev.dao;

import dev.model.User;
import dev.database.DatabaseConnection;
import java.lang.reflect.Field;
import java.sql.*;

public class UserDao {

    public boolean save(User user) {

        // TODO:
        // Insert user into database
        String sql = "insert into users (username, password, email) values (?, ?, ?) ";
        try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)){
            Field usernameField = User.class.getDeclaredField("username");
            Field passwordField = User.class.getDeclaredField("password");
            Field emailField = User.class.getDeclaredField("email");
            usernameField.setAccessible(true);
            passwordField.setAccessible(true);
            emailField.setAccessible(true);
            stmt.setString(1, (String) usernameField.get(user));
            stmt.setString(2, (String) passwordField.get(user));
            stmt.setString(3, (String) emailField.get(user));

            int rowsInserted = stmt.executeUpdate();
            return rowsInserted > 0;
        }
        catch (SQLException | NoSuchFieldException | IllegalAccessException ex){
            ex.printStackTrace();
            return false;
        }
    }

    public User findByUsername(String username) {

        // TODO:
        // Find a user by username
        String sql = "SELECT * FROM users WHERE username = ?";
        try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)){
            stmt.setString(1, username);
            try (ResultSet rs = stmt.executeQuery()){
                if (rs.next()){
                    User user = new User();
                    Field idField = User.class.getDeclaredField("id");
                    Field usernameField = User.class.getDeclaredField("username");
                    Field passwordField = User.class.getDeclaredField("password");
                    Field emailField = User.class.getDeclaredField("email");
                    idField.setAccessible(true);
                    usernameField.setAccessible(true);
                    passwordField.setAccessible(true);
                    emailField.setAccessible(true);
                    idField.set(user, rs.getInt("id"));
                    usernameField.set(user, rs.getString("username"));
                    passwordField.set(user, rs.getString("password"));
                    emailField.set(user, rs.getString("email"));
                    return user;
                }
            }
        }
        catch (SQLException | NoSuchFieldException | IllegalAccessException e){
            e.printStackTrace();
        }

        return null;
    }

}