package com.msksbr.MainFrm.MenuItemDiaog.Adder;

import com.msksbr.LoginFrm.ScreenSize;
import com.msksbr.SQL.Connector;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.Book;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BookAdder extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JTextField textField1;
    private JTextField textField2;
    private JTextField IDField;
    private JTextField textField4;
    private Connector connector;
    private int bID;
    private String bName;
    private String bType;
    private String ISBN;
    private String sql;

    public BookAdder() {

        try {
            connector = new Connector();
            bID = getBookMaxID() + 1;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        IDField.setText(String.valueOf(bID));
        IDField.setEditable(false);

        setTitle("添加图书信息");
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        setResizable(false);
        pack();
        setLocation();
        setVisible(true);

    }

    private void onOK() {
        bName = textField1.getText();
        bType = textField2.getText();
        ISBN = textField4.getText();
        sql = "INSERT INTO books (book_name,book_id,book_type,ISBN) VALUES ('" + bName + "'," + bID + ",'" + bType + "','" + ISBN + "');";
        commit2SQL();
        // 在此处添加您的代码
        dispose();
    }

    public int getBookMaxID() throws SQLException {
        ResultSet rs = connector.executeQuery("SELECT MAX(book_id) FROM books;");
        rs.next();
        return rs.getInt("MAX(book_id)");
    }

    public void setLocation() {
        setLocation(new ScreenSize().width / 2 - getWidth() / 2, new ScreenSize().height / 2 - getHeight() / 2);
    }

    private void commit2SQL() {
        try {
            connector.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
