package CHAPTER15;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class UserRegistrationApp {
    // MySQL 접속 정보
    private static final String DB_URL = "jdbc:mysql://localhost:3306/course";
    private static final String DB_USER = "root"; // MySQL 사용자명
    private static final String DB_PASSWORD = "123456789"; // MySQL 비밀번호    

    public UserRegistrationApp() {
        JFrame frame = new JFrame("회원가입");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 250);
        frame.setLayout(new GridLayout(4, 2));

        JLabel lblUsername = new JLabel("사용자명:");
        JTextField txtUsername = new JTextField();
        JLabel lblEmail = new JLabel("이메일:");
        JTextField txtEmail = new JTextField();
        JLabel lblPassword = new JLabel("비밀번호:");
        JPasswordField txtPassword = new JPasswordField();

        JButton btnRegister = new JButton("가입하기");

        btnRegister.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = txtUsername.getText();
                String email = txtEmail.getText();
                String password = new String(txtPassword.getPassword());

                if (registerUser(username, email, password)) {
                    JOptionPane.showMessageDialog(frame, "회원 가입 성공!");
                } else {
                    JOptionPane.showMessageDialog(frame, "회원 가입 실패!", "오류", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        frame.add(lblUsername);
        frame.add(txtUsername);
        frame.add(lblEmail);
        frame.add(txtEmail);
        frame.add(lblPassword);
        frame.add(txtPassword);
        frame.add(btnRegister);

        frame.setVisible(true);
    }

    // 회원 등록 메서드
    private boolean registerUser(String username, String email, String password) {
        String sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);
            pstmt.setString(2, email);
            pstmt.setString(3, password);
            int rowsInserted = pstmt.executeUpdate();

            return rowsInserted > 0; // 성공 여부 반환
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(UserRegistrationApp::new);
    }
}
