aboutsummaryrefslogtreecommitdiff
path: root/src/Store/Book.java
blob: fe2d63eb895360f1965a27ee7114d8f8a816ef87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package Store;

import Server.JSONMessage;
import Server.SocketServer;
import UI.MainWindow;
import com.corundumstudio.socketio.listener.DataListener;

import java.sql.*;
import java.util.ArrayList;
import java.util.Map;

public class Book {
    private int id;
    private String title;
    private String author;
    private int issuedBy;
    private String issuedByName = "";

    public Book(int id) {
        this.id = id;
    }

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
        this.issuedBy = 0; // 0 means available since IDs start with 1
    }

    public Book(int id, String title, String author, int issuedBy, String issuedByName) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.issuedBy = issuedBy;
        this.issuedByName = issuedByName;
    }

    public String getTitle() {
        return this.title;
    }

    public String getAuthor() {
        return this.author;
    }

    public int getIssuedBy() {
        return this.issuedBy;
    }

    public int getId() {
        return this.id;
    }

    public String getIssuedByName() {
        return issuedByName;
    }

    public int bookIssuedBy() throws SQLException {
        String sql = "SELECT issuedBy from Book where ID = " + this.id;
        Statement statement = ConnectionHandler.connection.createStatement();

        ResultSet response = statement.executeQuery(sql);
        while (response.next()) {
            return response.getInt("issuedBy");
        }

        return 0;
    }

    public boolean issue(int userId) throws SQLException {
        if (bookIssuedBy() == 0) {
            String sql = "UPDATE Book SET issuedBy = ? where ID = ?";
            PreparedStatement statement = ConnectionHandler.connection.prepareStatement(sql);

            statement.setInt(1, userId);
            statement.setInt(2, this.id);

            statement.executeUpdate();

            ArrayList<Book> allBooks = Book.getAll(false);
            UI.Components.BooksList.refreshBooks(allBooks);
            if (MainWindow.serverStarted) {
                SocketServer.server.getBroadcastOperations().sendEvent("booksUpdated", allBooks);
            }

            return true;
        }

        return false;
    }

    public boolean returnBook(int userId) throws SQLException {
        if (bookIssuedBy() == userId) {
            String sql = "UPDATE Book SET issuedBy = 0 where ID = ?";
            PreparedStatement statement = ConnectionHandler.connection.prepareStatement(sql);

            statement.setInt(1, this.id);

            statement.executeUpdate();

            ArrayList<Book> allBooks = Book.getAll(false);
            UI.Components.BooksList.refreshBooks(allBooks);
            if (MainWindow.serverStarted) {
                SocketServer.server.getBroadcastOperations().sendEvent("booksUpdated", allBooks);
            }

            return true;
        }

        return false;
    }

    public void save() throws SQLException {
        String sql = "INSERT INTO Book (title, author, issuedBy) VALUES (?, ?, ?)";

        PreparedStatement statement = ConnectionHandler.connection.prepareStatement(sql);

        statement.setString(1, title);
        statement.setString(2, author);
        statement.setInt(3, issuedBy);

        statement.executeUpdate();

        ArrayList<Book> allBooks = Book.getAll(false);
        UI.Components.BooksList.refreshBooks(allBooks);
        if (MainWindow.serverStarted) {
            SocketServer.server.getBroadcastOperations().sendEvent("booksUpdated", allBooks);
        }
    }

    public void delete() throws SQLException {
        String sql = "DELETE FROM Book WHERE ID = ?";
        PreparedStatement statement = ConnectionHandler.connection.prepareStatement(sql);

        statement.setInt(1, this.id);

        statement.executeUpdate();

        ArrayList<Book> allBooks = Book.getAll(false);
        UI.Components.BooksList.refreshBooks(allBooks);
        if (MainWindow.serverStarted) {
            SocketServer.server.getBroadcastOperations().sendEvent("booksUpdated", allBooks);
        }
    }

    public static ArrayList<Book> getAll(boolean availableOnly) throws SQLException {
        ArrayList<Book> books = new ArrayList<>();

        String sql;
        if (availableOnly) {
            sql = "SELECT * FROM Book WHERE issuedBy = 0";
        } else {
            sql = "SELECT Book.ID, Book.title, Book.issuedBy, Book.author, " +
                    "User.userName FROM Book LEFT JOIN User ON User.ID = Book.issuedBy";
        }
        Statement statement = ConnectionHandler.connection.createStatement();

        ResultSet response = statement.executeQuery(sql);
        while (response.next()) {
            books.add(new Book(response.getInt("ID"), response.getString("title"), response.getString("author"), response.getInt("issuedBy"), response.getString("userName")));
        }

        return books;
    }

    public static DataListener<JSONMessage> getListHandler(boolean availableOnly) {
        return ((client, data, ackSender) -> {
            Thread t = new Thread(() -> {
                ArrayList<Book> books = null;
                try {
                    books = getAll(availableOnly);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                client.sendEvent(availableOnly ? "availableBooksList" : "allBooksList", books);
            });

            t.start();
            t.join();
        });
    }

    public static DataListener<JSONMessage> issueHandler() {
        return ((client, data, ackSender) -> {
            Thread t = new Thread(() -> {
                Map d = data.getData();

                int userId = (int) d.get("id");
                Book b = new Book((int) d.get("bookId"));

                try {
                    if (b.issue(userId)) {
                        client.sendEvent("issued");
                    } else {
                        client.sendEvent("alreadyIssued");
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            });

            t.start();
            t.join();
        });
    }

    public static DataListener<JSONMessage> returnHandler() {
        return ((client, data, ackSender) -> {
            Thread t = new Thread(() -> {
                Map d = data.getData();

                int userId = (int) d.get("id");
                Book b = new Book((int) d.get("bookId"));

                try {
                    if (b.returnBook(userId)) {
                        client.sendEvent("returned");
                    } else {
                        client.sendEvent("returnFailed");
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            });

            t.start();
            t.join();
        });
    }

    public static void createTable() throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS Book (" +
                "ID INTEGER NOT NULL PRIMARY KEY, " +
                "title TEXT NOT NULL, " +
                "author text NOT NULL, " +
                "issuedBy INTEGER NOT NULL," +
                "FOREIGN KEY(issuedBy) REFERENCES User(ID)" +
                ");";

        Statement statement = ConnectionHandler.connection.createStatement();
        statement.execute(sql);
    }
}