package dev.dao;


import dev.database.DatabaseConnection;
import dev.model.User;


import java.sql.*;



public class UserDao {



    public boolean save(User user){


        String sql =
                "INSERT INTO users(username,password,email) VALUES(?,?,?)";


        try(Connection con =
                    DatabaseConnection.getConnection();

            PreparedStatement ps =
                    con.prepareStatement(sql)){


            ps.setString(1,user.getUsername());

            ps.setString(2,user.getPassword());

            ps.setString(3,user.getEmail());


            ps.executeUpdate();


            return true;


        }catch(SQLException e){

            e.printStackTrace();

        }


        return false;

    }





    public User findByUsername(String username){


        String sql =
                "SELECT * FROM users WHERE username=?";


        try(Connection con =
                    DatabaseConnection.getConnection();

            PreparedStatement ps =
                    con.prepareStatement(sql)){


            ps.setString(1,username);



            ResultSet rs=ps.executeQuery();



            if(rs.next()){


                return new User(

                        rs.getInt("id"),

                        rs.getString("username"),

                        rs.getString("password"),

                        rs.getString("email")

                );

            }


        }catch(SQLException e){

            e.printStackTrace();

        }


        return null;

    }

}