aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/database/Database.java
blob: a25e113b0a3390d3ba46750c699a4f1788e0b750 (plain) (blame)
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package database;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import models.Ability;
import models.AbilityType;
import models.GameStatus;
import models.History;
import models.Monster;
import models.MonsterViewModel;
import models.User;
import pokemon.Game;

public class Database {
	private Connection conn;
	static Database instance=null;
	
	private Database() {
		String connString="jdbc:mysql://localhost:3306/pokemon?user=root&password=";
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn=DriverManager.getConnection(connString);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Database getInstance() {
		if(instance==null)
			instance=new Database();
		return instance;
	}
	public boolean addUser(User user) {
		boolean res=false;
		String sql="SELECT * FROM user where username=? ";
		PreparedStatement ps;
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ResultSet result=ps.executeQuery();
			if(result.next()) {
				return res;
			}
			
			
			sql="INSERT INTO user(username,password,admin) values(?,?,?)";
			ps=conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			String hashedPassword=BcryptHelper.hashPasword(user.getPassword());
			ps.setString(2, hashedPassword);
			ps.setBoolean(3, user.isAdmin());
			if(ps.executeUpdate()==1) {
				res=true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
			
		
		return res;
	}
	public User login(User user) {
		User tempUser=null;
		String sql="SELECT * FROM user where username=?";
		try {
			PreparedStatement pre=conn.prepareStatement(sql);
			pre.setString(1, user.getUsername());
			ResultSet res=pre.executeQuery();
			if(res.next()) {
				String hashedPw=res.getString("password");
				if(BcryptHelper.checkPassword(user.password, hashedPw))
				{
					tempUser=new User();
					tempUser.setId(res.getInt("id"));
					tempUser.setAdmin(res.getBoolean("admin"));
					tempUser.setUsername(user.getUsername());
					tempUser.setmonsterId(res.getLong("pokemonId"));
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return tempUser;
		
	}
	public long addMonster(Monster monster) {
		long tempId=0;
		String sql=null;
		PreparedStatement ps;
		try {
			sql="INSERT INTO monster(name,description,hp,base64Image) values(?,?,?,?)";
			ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, monster.getName());
			ps.setString(2, monster.getDescription());
			ps.setInt(3, monster.getHp());
			ps.setString(4, monster.getBase64Image());
			if(ps.executeUpdate()==1) {
				try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
		            if (generatedKeys.next()) {
		                tempId=generatedKeys.getLong(1);
		            }
		            else {
		                throw new SQLException("Creating user failed, no ID obtained.");
		            }
		        }
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tempId;
	}
	public boolean addAbility(Ability ability) {
		boolean result=false;
		String sql=null;
		PreparedStatement ps;
		try {
			sql="INSERT INTO ability(monsterId,name,description,type,power) values(?,?,?,?,?)";
			ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			ps.setLong(1, ability.getMonsterId());
			ps.setString(2, ability.getName());
			ps.setString(3, ability.getDescription());
			ps.setInt(4, ability.getType().ordinal());
			ps.setFloat(5, ability.getPower());
			if(ps.executeUpdate()==1) {
				result=true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	public ArrayList<Monster> getMonsters(){
		ArrayList<Monster> monsters=new ArrayList<Monster>();
		
		String sql="SELECT * FROM monster";
		try {
			Statement statement = conn.createStatement();
			ResultSet res=statement.executeQuery(sql);
			while(res.next()) {
				Monster m=new Monster();
				m.setId(res.getLong("id"));
				m.setName(res.getString("name"));
				m.setDescription(res.getString("description"));
				m.setHp(res.getInt("hp"));
				m.setBase64Image(res.getString("base64Image"));
				monsters.add(m);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return monsters;
	}
	public Monster getUserMonster(String username) {
		Monster monster=null;
		String sql="SELECT * FROM monster m JOIN user u ON u.username=? AND u.pokemonId=m.id";
		try {
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setString(1, username);
			ResultSet res=statement.executeQuery();
			if(res.next()) {
				 monster=new Monster();
				 monster.setId(res.getLong("m.id"));
				 monster.setName(res.getString("m.name"));
				 monster.setDescription(res.getString("m.description"));
				 monster.setHp(res.getInt("m.hp"));
				 monster.setBase64Image(res.getString("m.base64Image"));
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return monster;
		
	}
	public void addMonsterToUser(long id,long monsterId) {
		
		String sql="UPDATE user set pokemonId=?  where id=?;";
		
		try {
			PreparedStatement ps=conn.prepareStatement(sql);
			ps=conn.prepareStatement(sql);
			ps.setLong(1,monsterId);
			ps.setLong(2, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public MonsterViewModel getMonsterViewModel(long id) {
		MonsterViewModel monster=null;
		
		String sql="SELECT * FROM monster m JOIN ability a ON m.id=? AND m.id=a.monsterId";
		try {
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setLong(1, id);
			ResultSet res=statement.executeQuery();
			int i=0;
			while(res.next()) {
				if(i==0)
				{
					monster=new MonsterViewModel();
					monster.setId(res.getLong("m.id"));
					monster.setName(res.getString("m.name"));
					monster.setDescription(res.getString("m.description"));
					monster.setHp(res.getInt("m.hp"));
					monster.setBase64Image(res.getString("m.base64Image"));
					monster.abilities=new ArrayList<Ability>();
					i++;
				}
				Ability a=new Ability();
				a.setId(res.getLong("a.id"));
				a.setMonsterId(res.getLong("m.id"));
				a.setName(res.getString("a.name"));
				a.setDescription(res.getString("a.description"));
				a.setType(AbilityType.values()[res.getInt("a.type")]);
				a.setPower(res.getFloat("a.power"));
				monster.abilities.add(a);
				 
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return monster;
		
	}
	public ArrayList<User> getAllUsers(){
		ArrayList<User> users=new ArrayList<User>();
		try {
			String sql="SELECT * FROM user";
			Statement statement = conn.createStatement();
			ResultSet res=statement.executeQuery(sql);
			while(res.next()) {
				User tempUser=new User();
				tempUser=new User();
				tempUser.setId(res.getLong("id"));
				tempUser.setAdmin(res.getBoolean("admin"));
				tempUser.setUsername(res.getString("username"));
				if(res.getObject("pokemonId")!=null)
					tempUser.setmonsterId(res.getLong("pokemonId"));
				else 
					tempUser.setmonsterId(-1);
				users.add(tempUser);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return users;
		
	}
	public void deleteUser(long id) {
		String sql="DELETE FROM user WHERE id=?";
		try {
			PreparedStatement preStatement=conn.prepareStatement(sql);
			preStatement.setLong(1, id);
			preStatement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void deleteMonster(long id) {
		try {
			conn.setAutoCommit(false);
			String sql="DELETE FROM ability WHERE monsterId=?";
			PreparedStatement pre = conn.prepareStatement(sql);
			pre.setLong(1, id);
			pre.executeUpdate();
			sql="DELETE FROM monster WHERE id=?";
			pre = conn.prepareStatement(sql);
			pre.setLong(1, id);
			pre.executeUpdate();
			sql="UPDATE user set pokemonId=null WHERE pokemonId=?";
			pre = conn.prepareStatement(sql);
			pre.setLong(1, id);
			pre.executeUpdate();
			
			conn.commit();

		} catch (SQLException  e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	public User getUserById(long id){
		User user=null;
		try {
			String sql="SELECT * FROM user WHERE id=?";
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setLong(1, id);
			ResultSet res=statement.executeQuery();
			if(res.next()) {
				user=new User();
				user.setId(res.getLong("id"));
				user.setAdmin(res.getBoolean("admin"));
				user.setUsername(res.getString("username"));
				if(res.getObject("pokemonId")!=null)
					user.setmonsterId(res.getLong("pokemonId"));
				else 
					user.setmonsterId(-1);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return user;
		
	}
	public int addHistory(Game game) throws Exception{
		Date date=new Date(Calendar.getInstance().getTimeInMillis());
		String sql="INSERT INTO history(player,pokemon,time,result) values(?,?,?,?),(?,?,?,?)";
		PreparedStatement ps=conn.prepareStatement(sql);
		if(game.getStatus()==GameStatus.PLAYER1WIN) {
			ps.setLong(1, game.player1Id);
			ps.setLong(2, game.monster1.id);
			ps.setDate(3, date);
			ps.setInt(4, 1);
			ps.setLong(5, game.player2Id);
			ps.setLong(6, game.monster2.id);
			ps.setDate(7, date);
			ps.setInt(8, 0);
		}else if(game.getStatus()==GameStatus.PLAYER2WIN) {
			ps.setLong(1, game.player1Id);
			ps.setLong(2, game.monster1.id);
			ps.setDate(3, date);
			ps.setInt(4, 0);
			ps.setLong(5, game.player2Id);
			ps.setLong(6, game.monster2.id);
			ps.setDate(7, date);
			ps.setInt(8, 1);
		}
		return ps.executeUpdate();
	}
	public ArrayList<History> getUserHistory(long id){
		ArrayList<History> history=new ArrayList<>();
		String sql="SELECT * FROM history where player=? ";
		try {
			PreparedStatement ps=conn.prepareStatement(sql);
			ps.setLong(1, id);
			ResultSet res=ps.executeQuery();
			while(res.next()) {
				History h=new History();
				h.pokemon=getMonsterViewModel(res.getLong("pokemon"));
				h.time=res.getDate("time");
				h.result=res.getInt("result");
				history.add(h);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return history;
		
	}

}