-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PlayerManager.cs
561 lines (490 loc) · 21.3 KB
/
PlayerManager.cs
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using System.Data.SQLite;
using System.Data;
using System.Diagnostics;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using Terminal.Gui;
using System.Data.Entity.Core.Metadata.Edm;
using System.Globalization;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace Capital_and_Cargo
{
internal class PlayerManager
{
private SqliteConnection _connection;
//add comment
public PlayerManager(ref SqliteConnection connection)
{
_connection = connection;
EnsureTableExistsAndIsPopulated();
}
public void EnsureTableExistsAndIsPopulated()
{
if (!TableExists("Player"))
{
CreatePlayerTable();
InitPlayerTable();
}
if (!TableExists("warehouse"))
{
CreateWarehouseTable();
}
if (!TableExists("MoneyHistory"))
{
CreateMoneyHistoryTable();
}
if(!TableExists("HistoryDetail"))
{
CreateHistoryDetailTable();
}
}
private void CreateHistoryDetailTable()
{
var sql = @"CREATE TABLE HistoryDetail (
Date TEXT,
Income REAL default 0,
Spend REAL default 0,
City TEXT,
CargoType TEXT,
Import INTEGER default 0,
Export INTEGER default 0,
Production INTEGER default 0
);
CREATE UNIQUE INDEX idx_city_date_cargo ON HistoryDetail (City, Date, CargoType);
CREATE INDEX idx_city_cargo ON HistoryDetail (City, CargoType);
CREATE INDEX idx_city ON HistoryDetail (City);
";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
private bool TableExists(string tableName)
{
string sql = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}';";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
var result = command.ExecuteScalar();
return result != null && result.ToString() == tableName;
}
}
private void CreatePlayerTable()
{
string sql = @"
CREATE TABLE Player (
Date TEXT NOT NULL,
Money REAL NOT NULL,
productionBonusPool INTEGER default 0,
displayStartPopup INTEGER NOT NULL default 0
);
";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
private void CreateMoneyHistoryTable()
{
string sql = @"
CREATE TABLE MoneyHistory (
Date TEXT NOT NULL,
Money REAL NOT NULL
);
";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
public void UpdateMoneyHistoryTable()
{
DataTable playerTable = LoadPlayer();
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
INSERT INTO MoneyHistory (Date, Money)
VALUES (@Date, @Money);";
command.Parameters.AddWithValue("@Date", playerTable.Rows[0]["Date"]);
command.Parameters.AddWithValue("@Money", playerTable.Rows[0]["Money"]);
command.ExecuteNonQuery();
}
}
public DateTime firstOfMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, 1);
}
public void InitPlayerTable()
{
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
INSERT INTO Player (Date, Money)
VALUES (@Date, @Money);";
command.Parameters.AddWithValue("@Date", "1910-11-07");//first cargo flight was on nov 7, 1910
command.Parameters.AddWithValue("@Money", 1000000);
command.ExecuteNonQuery();
}
}
private void CreateWarehouseTable()
{
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
CREATE TABLE IF NOT EXISTS warehouse (
CityName TEXT NOT NULL,
CargoType String NOT NULL,
Amount INTEGER NOT NULL,
PurchasePrice REAL NOT NULL
);";
command.ExecuteNonQuery();
}
}
private void cleanupWarehouse()
{
//delete from warehouse where amount is 0
//TODO :
using (var transaction = _connection.BeginTransaction())
{
//Remove goods with 0 amounts
using (var command = _connection.CreateCommand())
{
command.CommandText = @"delete from warehouse where amount <= 0";
int affected = command.ExecuteNonQuery();
if (affected > 0)
{
Debug.WriteLine("Cleaning up the warehouse");
}
}
try
{
//if there are multiple records for the same resource in the warehouse of a city, merge them
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
-- Create a temporary table to store aggregated results
CREATE TEMPORARY TABLE warehouse_temp AS
SELECT CityName, CargoType, SUM(Amount) AS TotalAmount, SUM(PurchasePrice) as PurchasePrice
FROM warehouse
GROUP BY CityName, CargoType;
-- Delete the original data from the `warehouse` table
DELETE FROM warehouse;
--Insert the aggregated data back into the `warehouse` table
INSERT INTO warehouse (CityName, CargoType, Amount,PurchasePrice)
SELECT CityName, CargoType, TotalAmount, PurchasePrice
FROM warehouse_temp;
--Drop the temporary table
DROP TABLE warehouse_temp;";
command.ExecuteNonQuery();
}
// Commit the transaction if both commands succeed
transaction.Commit();
}
catch (Exception ex)
{
Debug.WriteLine($"An error making a purchase: {ex.Message}");
// Rollback the transaction on error
transaction.Rollback();
}
}
}
public DataTable loadWarehouse(String city)
{
cleanupWarehouse();
DataTable dataTable = new DataTable();
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
SELECT CargoType, Amount, (PurchasePrice / Amount) as [Cost], PurchasePrice as Value
FROM warehouse
WHERE CityName = @CityName
ORDER BY CargoType;";
// Use parameters to prevent SQL injection
command.Parameters.AddWithValue("@CityName", city);
using (var reader = command.ExecuteReader())
{
dataTable.Load(reader);
}
}
return dataTable;
}
public DataTable getMaxSellAmount(string city, string cargoType)
{
DataTable maxSellAmount = new DataTable();
string sql = "SELECT Amount FROM warehouse WHERE CityName = @city AND CargoType = @cargoType;";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@cargoType", cargoType);
using (var reader = command.ExecuteReader())
{
maxSellAmount.Load(reader);
}
}
return maxSellAmount;
}
public void purchase(String city, String CargoType, int amount, Double price)
{
using (var transaction = _connection.BeginTransaction())
{
try
{
//Decrease market supply
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Removing " + amount + " of " + CargoType + " from " + city + " market");
command.CommandText = @"
UPDATE city_market SET SupplyAmount = (SupplyAmount - @amount ) WHERE CargoType = @cargoType and CityName = @city
";
command.Parameters.AddWithValue("@cargoType", CargoType);
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@amount", amount);
command.ExecuteNonQuery();
}
//Manage Reputation
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
UPDATE cities SET Bought = Bought + @amount where city = @city
";
command.Parameters.AddWithValue("@amount", amount);
command.Parameters.AddWithValue("@city", city);
command.ExecuteNonQuery();
}
//Pay
Double totalPrice = amount * price;
pay(totalPrice,city, CargoType);
//Add to Warehouse
int recordsAffected = 0;
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Adding " + amount + " of " + CargoType + " to " + city + " warehouse");
command.CommandText = @"
UPDATE warehouse SET Amount = Amount + @amount, PurchasePrice = PurchasePrice + @Price WHERE CityName = @city AND CargoType = @cargoType
";
command.Parameters.AddWithValue("@cargoType", CargoType);
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@amount", amount);
command.Parameters.AddWithValue("@Price", totalPrice);
recordsAffected = command.ExecuteNonQuery();
}
if (recordsAffected == 0)
{
//This cargo wasn't in the warehouse yet, add it
using (var cmdInsert = _connection.CreateCommand())
{
cmdInsert.CommandText = @"
INSERT INTO warehouse (CityName, CargoType, Amount, PurchasePrice) VALUES (@city, @cargoType, @amount,@Price)
";
cmdInsert.Parameters.AddWithValue("@cargoType", CargoType);
cmdInsert.Parameters.AddWithValue("@city", city);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@Price", totalPrice);
cmdInsert.ExecuteNonQuery();
}
}
// Commit the transaction if both commands succeed
transaction.Commit();
}
catch (Exception ex)
{
Debug.WriteLine($"An error making a purchase: {ex.Message}");
// Rollback the transaction on error
transaction.Rollback();
}
}
}
public void pay(double totalPrice,String city, String CargoType)
{
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Paying " + totalPrice);
command.CommandText = @"
UPDATE player SET money = money - @price
";
command.Parameters.AddWithValue("@price", totalPrice);
command.ExecuteNonQuery();
}
//Keep track of money paid
DateTime firstOfMonthDate = firstOfMonth(getCurrentDate());
var sql = @"INSERT INTO HistoryDetail (City, Date, CargoType, Spend)
VALUES (@city, @date, @CargoType, @Spend)
ON CONFLICT (City, Date, CargoType)
DO UPDATE SET Spend = Spend + excluded.Spend;";
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Storing income history " + firstOfMonthDate + "\t" + totalPrice + "\t" + city + "\t" + CargoType);
command.CommandText = sql;
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@date", firstOfMonthDate);
command.Parameters.AddWithValue("@CargoType", CargoType);
command.Parameters.AddWithValue("@Spend", totalPrice);
command.ExecuteNonQuery();
}
}
public void sell(String city, String CargoType, Int64 amount, Double price)
{
/* using (var transaction = _connection.BeginTransaction())
{
try
{*/
//Increase market supply
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Adding " + amount + " of " + CargoType + " to " + city + " market");
command.CommandText = @"
UPDATE city_market SET SupplyAmount = SupplyAmount + @amount WHERE CargoType = @cargoType and CityName = @city
";
command.Parameters.AddWithValue("@cargoType", CargoType);
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@amount", amount);
command.ExecuteNonQuery();
}
//Get Payed
Double totalPrice = amount * price;
receiveMoney(totalPrice, city, CargoType);
//Manage Reputation
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
UPDATE cities SET SOld = Sold + @amount where city = @city
";
command.Parameters.AddWithValue("@amount", amount);
command.Parameters.AddWithValue("@city", city);
command.ExecuteNonQuery();
}
//Remove from to Warehouse
int recordsAffected = 0;
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Removing " + amount + " of " + CargoType + " from " + city + " warehouse");
command.CommandText = @"
UPDATE warehouse SET Amount = Amount - @amount, PurchasePrice = PurchasePrice - @price WHERE CityName = @city AND CargoType = @cargoType
";
command.Parameters.AddWithValue("@cargoType", CargoType);
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@amount", amount);
command.Parameters.AddWithValue("@price", totalPrice);
recordsAffected = command.ExecuteNonQuery();
}
// Commit the transaction if both commands succeed
/* transaction.Commit();
}
catch (Exception ex)
{
Debug.WriteLine($"An error making a sale: {ex.Message}");
// Rollback the transaction on error
transaction.Rollback();
}
}*/
}
private void receiveMoney(Double money, String city, String CargoType)
{
//Handle receiving money
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Getting Payed " + money);
command.CommandText = @"
UPDATE player SET money = money + @price
";
command.Parameters.AddWithValue("@price", money);
command.ExecuteNonQuery();
}
//Keep track of money received
DateTime firstOfMonthDate = firstOfMonth(getCurrentDate());
var sql = @"INSERT INTO HistoryDetail (City, Date, CargoType, Income)
VALUES (@city, @date, @CargoType, @Income)
ON CONFLICT (City, Date, CargoType)
DO UPDATE SET Income = Income + excluded.Income;";
using (var command = _connection.CreateCommand())
{
Debug.WriteLine("Storing income history " + firstOfMonthDate + "\t" + money + "\t" + city + "\t" + CargoType);
command.CommandText = sql;
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@date", firstOfMonthDate);
command.Parameters.AddWithValue("@CargoType", CargoType);
command.Parameters.AddWithValue("@Income", money);
command.ExecuteNonQuery();
}
SoundMananger soundMananger = new SoundMananger();
soundMananger.playSound(Properties.Resources.moneyGained);
}
public DataTable LoadPlayer()
{
DataTable dataTable = new DataTable();
string sql = "SELECT Date, Money,productionBonusPool,displayStartPopup from Player";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
using (var reader = command.ExecuteReader())
{
dataTable.Load(reader);
}
}
return dataTable;
}
public DataTable LoadPlayerHistory(int limit)
{
DataTable dataTable = new DataTable();
string sql = "select * from (SELECT Date, Money from MoneyHistory order by Date desc limit 0,@limit ) a order by date asc";
using (var command = _connection.CreateCommand())
{
command.CommandText = sql;
command.Parameters.AddWithValue("@limit", limit);
using (var reader = command.ExecuteReader())
{
dataTable.Load(reader);
}
}
return dataTable;
}
public void nextDay()
{
using (var command = _connection.CreateCommand())
{
command.CommandText = @"
UPDATE Player
SET Date = date(Date, '+1 day');";
command.ExecuteNonQuery();
}
//
}
public DateTime getCurrentDate() {
DateTime currentDate = new DateTime();
using (var command = _connection.CreateCommand())
{
command.CommandText = "select Date from player";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var eventDate = reader["Date"];
currentDate = DateTime.ParseExact((String)reader["Date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
}
}
return currentDate;
}
public void displayPopup(int value)
{
string updateQuery = @"
UPDATE Player
SET displayStartPopup = @value;";
using (var command = _connection.CreateCommand())
{
command.CommandText = updateQuery;
command.Parameters.AddWithValue(@"value", value);
command.ExecuteNonQuery();
}
}
}
}