Database.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Mono.Data.Sqlite;
  5. using System.Data;
  6. using System;
  7. using UnityEngine.Networking;
  8. using System.IO;
  9. public class Database : MonoBehaviour {
  10. private const string onlineQuestionsUrl = "nordh.xyz/narKampen/dbFiles/Question.php";
  11. private const string serverUrl = "nordh.xyz/narKampen/dbFiles/";
  12. string connectionType;
  13. string databaseUrl;
  14. string gameMode;
  15. int winAmount = -1;
  16. int questionTimer = -1;
  17. public GameObject questionCardPrefab;
  18. private static Database instance;
  19. public static Database Instance { get { return instance; } }
  20. IDbConnection conn;
  21. private void Awake() {
  22. if (instance == null) {
  23. instance = this;
  24. }
  25. }
  26. internal void GetCategories(List<CategoryPanel.Category> list, string gameMode) {
  27. if (gameMode.Equals("Online")) {
  28. OnlineDatabase.Instance.GetCategories(list);
  29. } else {
  30. string sql = "SELECT name, r, g, b, a, id FROM category";
  31. IDbCommand cmd = GetConnection();
  32. cmd.CommandText = sql;
  33. IDataReader reader = cmd.ExecuteReader();
  34. while (reader.Read()) {
  35. CategoryPanel.Category cat = new CategoryPanel.Category();
  36. byte r = (byte)reader.GetInt32(1);
  37. byte g = (byte)reader.GetInt32(2);
  38. byte b = (byte)reader.GetInt32(3);
  39. byte a = (byte)reader.GetInt32(4);
  40. cat.color = new Color32(r, g, b, a);
  41. cat.name = reader.GetString(0);
  42. cat.id = reader.GetInt32(5);
  43. list.Add(cat);
  44. }
  45. CloseConnection();
  46. }
  47. }
  48. [Serializable]
  49. public class Question {
  50. public string question;
  51. public string answer;
  52. public string id;
  53. public string category;
  54. }
  55. [Serializable]
  56. public class Questions {
  57. public List<Question> questionsList = new List<Question>();
  58. }
  59. [Serializable]
  60. public class PlayerInfo {
  61. public string username;
  62. public string status;
  63. }
  64. [Serializable]
  65. public class PlayerInfos {
  66. public List<PlayerInfo> playerInfoList = new List<PlayerInfo>();
  67. }
  68. [Serializable]
  69. public class Category {
  70. public int r;
  71. public int g;
  72. public int b;
  73. public int a;
  74. public int id;
  75. public string name;
  76. }
  77. [Serializable]
  78. public class Categories {
  79. public List<Category> categoryList = new List<Category>();
  80. }
  81. [Serializable]
  82. public class OnlineGame {
  83. public string id;
  84. public string winNumber;
  85. public string answerTimer;
  86. public string roundTimeLimit;
  87. public string currentPlayer;
  88. public string round;
  89. public string startDate;
  90. public string LastPlayedDate;
  91. public string finishedDate;
  92. public string status;
  93. }
  94. [Serializable]
  95. public class OnlineGames {
  96. public List<OnlineGame> onlineGamesList = new List<OnlineGame>();
  97. }
  98. [Serializable]
  99. public class UserName {
  100. public string id;
  101. public string username;
  102. }
  103. [Serializable]
  104. public class UserNames {
  105. public List<UserName> usernamesList = new List<UserName>();
  106. }
  107. internal void SetLastPlayedDate(int gameId) {
  108. if (gameMode.Equals("Online")) {
  109. }
  110. string sql = "UPDATE game SET lastPlayedDate = DATE() WHERE id = " + gameId;
  111. IDbCommand cmd = GetConnection();
  112. cmd.CommandText = sql;
  113. cmd.ExecuteNonQuery();
  114. cmd.Dispose();
  115. CloseConnection();
  116. }
  117. private IDbCommand GetConnection() {
  118. if (databaseUrl == null) { // ej bra lösning för online
  119. SetLocalOrOnline("Local");
  120. }
  121. conn = new SqliteConnection(databaseUrl);
  122. conn.Open();
  123. IDbCommand cmd = conn.CreateCommand();
  124. return cmd;
  125. }
  126. private void CloseConnection() {
  127. conn.Close();
  128. }
  129. string questionString = "";
  130. string answerString = "";
  131. string idString = "";
  132. string categoryString = "";
  133. private int round = -1;
  134. private string SearchString;
  135. public string QuestionString { get => questionString; set => questionString = value; }
  136. private void Start() {
  137. if (instance == null) {
  138. instance = this;
  139. }
  140. if (databaseUrl == null || databaseUrl.Equals("")) {
  141. SetLocalOrOnline("Local"); // Temporary, should not be needed after local testing
  142. }
  143. }
  144. internal void KeepSignedIn(string username, int userId, bool keepSigendIn) {
  145. int ksi = 0;
  146. if (keepSigendIn) {
  147. ksi = 1;
  148. }
  149. string sql = "INSERT OR REPLACE INTO userSettings (username, userId, keepSignedIn) VALUES ('" + username + "', " + userId + "," + ksi + ")";
  150. IDbCommand cmd = GetConnection();
  151. cmd.CommandText = sql;
  152. cmd.ExecuteNonQuery();
  153. CloseConnection();
  154. }
  155. internal bool IsKeepSignedIn() {
  156. string sql = "SELECT keepSignedIn FROM userSettings";
  157. IDbCommand cmd = GetConnection();
  158. cmd.CommandText = sql;
  159. IDataReader reader = cmd.ExecuteReader();
  160. int res = 0;
  161. while (reader.Read()) {
  162. res = reader.GetInt32(0);
  163. }
  164. return res == 1;
  165. }
  166. internal KeyValuePair<int, string> GetSignedInUser() {
  167. string sql = "SELECT userId, username FROM userSettings";
  168. IDbCommand cmd = GetConnection();
  169. cmd.CommandText = sql;
  170. int userId = -1;
  171. string username = "";
  172. IDataReader reader = cmd.ExecuteReader();
  173. while (reader.Read()) {
  174. userId = reader.GetInt32(0);
  175. username = reader.GetString(1);
  176. }
  177. CloseConnection();
  178. return new KeyValuePair<int, string>(userId, username);
  179. }
  180. internal void LogoutUser() {
  181. // string sql = "UPDATE userSettings SET keepSignedIn = 0";
  182. string sql = "DELETE FROM userSettings";
  183. IDbCommand cmd = GetConnection();
  184. cmd.CommandText = sql;
  185. cmd.ExecuteNonQuery();
  186. CloseConnection();
  187. }
  188. internal int GetQuestionTimer(int gameId, string gameMode) {
  189. if (questionTimer == -1) {
  190. string sql = "SELECT answerTimer FROM game WHERE id = " + gameId;
  191. if (databaseUrl == null) {
  192. SetLocalOrOnline("Local");
  193. }
  194. IDbCommand cmd = GetConnection();
  195. cmd.CommandText = sql;
  196. IDataReader reader = cmd.ExecuteReader();
  197. while (reader.Read()) {
  198. questionTimer = reader.GetInt32(0);
  199. }
  200. reader.Close();
  201. cmd.Dispose();
  202. }
  203. CloseConnection();
  204. return this.questionTimer;
  205. }
  206. internal List<LocalGameScript> GetLocalGames(GameObject prefab) {
  207. List<LocalGameScript> games = new List<LocalGameScript>();
  208. string sql = "SELECT game.*, name, localUsers.id as userId FROM game INNER JOIN localGamePlayers on game.id = localGamePlayers.gameId INNER JOIN localUsers on playerId = localUsers.id order by game.id ASC, userId ASC";
  209. IDbConnection conn = new SqliteConnection(databaseUrl);
  210. conn.Open();
  211. IDbCommand cmd = conn.CreateCommand();
  212. cmd.CommandText = sql;
  213. IDataReader reader = cmd.ExecuteReader();
  214. int currentGame = -1;
  215. GameObject localGame;
  216. LocalGameScript lgs = null;
  217. string currentPlayerName = "";
  218. int currentPoints = 0;
  219. while (reader.Read()) {
  220. if (currentGame != reader.GetInt32(0)) {
  221. localGame = Instantiate(prefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  222. lgs = localGame.GetComponent<LocalGameScript>();
  223. lgs.GameId = reader.GetInt32(0);
  224. lgs.GameMode = reader.GetString(1);
  225. lgs.QuestionsNeededToWin = reader.GetInt32(2).ToString();
  226. lgs.AnswerTimer = reader.GetInt32(3);
  227. lgs.NumberOfPlayers = reader.GetInt32(4).ToString();
  228. lgs.CurrentPlayer = reader.GetString(5);
  229. lgs.Round = reader.GetInt32(6).ToString();
  230. lgs.StartDate = reader.GetString(7);
  231. lgs.LastPlayedDate = reader.GetString(8);
  232. lgs.FinishedDate = reader.IsDBNull(9) ? "" : reader.GetString(9);
  233. currentPlayerName = reader.GetString(10);
  234. currentPoints = GetPlayerPoints(reader.GetInt32(0), currentPlayerName);
  235. lgs.AddPlayer(currentPlayerName, currentPoints);
  236. games.Add(lgs);
  237. } else if (currentGame == reader.GetInt32(0)) {
  238. currentPlayerName = reader.GetString(10);
  239. currentPoints = GetPlayerPoints(currentGame, currentPlayerName);
  240. lgs.AddPlayer(currentPlayerName, currentPoints);
  241. }
  242. currentGame = reader.GetInt32(0);
  243. }
  244. reader.Close();
  245. cmd.Dispose();
  246. conn.Close();
  247. return games;
  248. }
  249. internal void SetQuestionsLost(int gameId, string playerName, int questionsLost) {
  250. string sql = "UPDATE localGamePlayers SET questionsLost = questionsLost + " + questionsLost + " WHERE gameId = " + gameId + " AND playerId = (SELECT id FROM localUsers WHERE name = '" + playerName + "')";
  251. IDbConnection conn = new SqliteConnection(databaseUrl);
  252. conn.Open();
  253. IDbCommand cmd = conn.CreateCommand();
  254. cmd.CommandText = sql;
  255. cmd.ExecuteNonQuery();
  256. cmd.Dispose();
  257. conn.Close();
  258. }
  259. internal void RemoveGame(int gameId) {
  260. string sql = "DELETE FROM game WHERE id = " + gameId;
  261. List<LocalGameScript> games = new List<LocalGameScript>();
  262. IDbConnection conn = new SqliteConnection(databaseUrl);
  263. conn.Open();
  264. IDbCommand cmd = conn.CreateCommand();
  265. cmd.CommandText = sql;
  266. cmd.ExecuteNonQuery();
  267. string deleteLockedQuestionsSql = "DELETE FROM usersLockedQuestions WHERE gameId = " + gameId;
  268. cmd.CommandText = deleteLockedQuestionsSql;
  269. cmd.ExecuteNonQuery();
  270. cmd.Dispose();
  271. conn.Close();
  272. }
  273. public string GetCurrentPlayer(int gameId, string gameMode) {
  274. if (gameMode.Equals("Online")) {
  275. return OnlineDatabase.Instance.GetCurrentPlayer(gameId);
  276. }
  277. string sql = "SELECT currentPlayer FROM game WHERE id = " + gameId;
  278. IDbConnection conn = new SqliteConnection(databaseUrl);
  279. conn.Open();
  280. IDbCommand cmd = conn.CreateCommand();
  281. cmd.CommandText = sql;
  282. IDataReader reader = cmd.ExecuteReader();
  283. string currentPlayer = "";
  284. while (reader.Read()) {
  285. currentPlayer = reader.GetString(0);
  286. }
  287. reader.Close();
  288. cmd.Dispose();
  289. conn.Close();
  290. return currentPlayer;
  291. }
  292. public void SetCurrentPlayer(int gameId, string currentPlayer, string gameMode) {
  293. if (gameMode.Equals("Online")) {
  294. OnlineDatabase.Instance.SetCurrentPlayer(gameId, currentPlayer);
  295. } else {
  296. string sql = "UPDATE game SET currentPlayer = '" + currentPlayer + "' WHERE id = " + gameId;
  297. IDbConnection conn = new SqliteConnection(databaseUrl);
  298. conn.Open();
  299. IDbCommand cmd = conn.CreateCommand();
  300. cmd.CommandText = sql;
  301. cmd.ExecuteNonQuery();
  302. cmd.Dispose();
  303. conn.Close();
  304. }
  305. }
  306. internal int GetPlayerPoints(int gameId, string playerName) {
  307. string sql = "SELECT count(*) FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerName + "'";
  308. IDbConnection conn = new SqliteConnection(databaseUrl);
  309. conn.Open();
  310. IDbCommand cmd = conn.CreateCommand();
  311. cmd.CommandText = sql;
  312. IDataReader reader = cmd.ExecuteReader();
  313. int points = 0;
  314. while (reader.Read()) {
  315. points = reader.GetInt32(0);
  316. }
  317. reader.Close();
  318. cmd.Dispose();
  319. conn.Close();
  320. return points;
  321. }
  322. internal void SetFinishedDate(int gameId, string finishedDate, string gameMode) {
  323. if (gameMode.Equals("Online")) {
  324. OnlineDatabase.Instance.SetFinishedDate(gameId, finishedDate);
  325. } else {
  326. string sql = "UPDATE game SET finishedDate = '" + finishedDate + "' WHERE id = " + gameId;
  327. IDbConnection conn = new SqliteConnection(databaseUrl);
  328. conn.Open();
  329. IDbCommand cmd = conn.CreateCommand();
  330. cmd.CommandText = sql;
  331. cmd.ExecuteNonQuery();
  332. cmd.Dispose();
  333. conn.Close();
  334. }
  335. }
  336. internal void SetRoundValue(int gameId, int round, string gameMode) {
  337. if (gameMode.Equals("Online")) {
  338. OnlineDatabase.Instance.SetRoundValue(gameId, round);
  339. } else {
  340. string sql = "UPDATE game SET round = " + round + " WHERE id = " + gameId;
  341. IDbConnection conn = new SqliteConnection(databaseUrl);
  342. conn.Open();
  343. IDbCommand cmd = conn.CreateCommand();
  344. cmd.CommandText = sql;
  345. cmd.ExecuteNonQuery();
  346. cmd.Dispose();
  347. conn.Close();
  348. }
  349. }
  350. internal int GetRoundValue(int gameId, string gameMode) {
  351. if (gameMode.Equals("Online")) {
  352. return OnlineDatabase.Instance.GetRoundValue(gameId);
  353. }
  354. if (this.round == -1) {
  355. string sql = "SELECT round FROM game WHERE id = " + gameId;
  356. IDbConnection conn = new SqliteConnection(databaseUrl);
  357. conn.Open();
  358. IDbCommand cmd = conn.CreateCommand();
  359. cmd.CommandText = sql;
  360. IDataReader reader = cmd.ExecuteReader();
  361. while (reader.Read()) {
  362. this.round = reader.GetInt32(0);
  363. }
  364. reader.Close();
  365. cmd.Dispose();
  366. conn.Close();
  367. }
  368. return this.round;
  369. }
  370. internal List<KeyValuePair<string, int>> GetPlayersForGame(int gameId, string gameMode) {
  371. if (gameMode.Equals("Online")) {
  372. return OnlineDatabase.Instance.GetPlayersForGame(gameId);
  373. }
  374. string sql = "SELECT name, (SELECT count(*) FROM usersLockedQuestions WHERE playerName = localUsers.name AND gameId = " + gameId + ") as numAnswers FROM localGamePlayers " +
  375. "LEFT JOIN localUsers ON localGamePlayers.playerId = localUsers.id " +
  376. "WHERE gameId = " + gameId;
  377. IDbConnection conn = new SqliteConnection(databaseUrl);
  378. conn.Open();
  379. IDbCommand cmd = conn.CreateCommand();
  380. cmd.CommandText = sql;
  381. IDataReader reader = cmd.ExecuteReader();
  382. List<KeyValuePair<string, int>> returnList = new List<KeyValuePair<string, int>>();
  383. while (reader.Read()) {
  384. KeyValuePair<string, int> player = new KeyValuePair<string, int>(reader.GetString(0), reader.GetInt32(1));
  385. returnList.Add(player);
  386. }
  387. return returnList;
  388. }
  389. public string AnswerString { get => answerString; set => answerString = value; }
  390. public string IdString { get => idString; set => idString = value; }
  391. public string CategoryString { get => categoryString; set => categoryString = value; }
  392. public void SetLocalOrOnline(string type) {
  393. gameMode = type;
  394. if (type.Equals("Local")) {
  395. string databaseName = "narKampenLocal.db";
  396. if (Application.platform == RuntimePlatform.Android) {
  397. databaseUrl = Application.persistentDataPath + "/" + databaseName;
  398. if (!File.Exists(databaseUrl)) {
  399. UnityWebRequest load = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + databaseName);
  400. load.SendWebRequest();
  401. while (!load.isDone) { }
  402. File.WriteAllBytes(databaseUrl, load.downloadHandler.data);
  403. }
  404. databaseUrl = "URI=file:" + databaseUrl;
  405. } else {
  406. databaseUrl = "URI=file:" + Application.dataPath + "/narKampenLocal.db";
  407. }
  408. } else {
  409. databaseUrl = onlineQuestionsUrl;
  410. }
  411. connectionType = type;
  412. }
  413. internal int GetQuestionsLost(int gameId, string playerName, string gameMode) {
  414. if (gameMode.Equals("Online")) {
  415. return OnlineDatabase.Instance.GetQuestionsLost(gameId, playerName);
  416. }
  417. string sql = "SELECT questionsLost FROM localGamePlayers WHERE gameId = " + gameId + " AND playerId = (SELECT id from localUsers WHERE name = '" + playerName + "')";
  418. IDbConnection conn = new SqliteConnection(databaseUrl);
  419. conn.Open();
  420. IDbCommand cmd = conn.CreateCommand();
  421. cmd.CommandText = sql;
  422. IDataReader reader = cmd.ExecuteReader();
  423. int returnValue = 0;
  424. while (reader.Read()) {
  425. returnValue = reader.GetInt32(0);
  426. }
  427. reader.Close();
  428. cmd.Dispose();
  429. conn.Close();
  430. return returnValue;
  431. }
  432. public string GetGameMode(int gameId) {
  433. if (this.gameMode == null) {
  434. string sql = "SELECT gameMode FROM game WHERE id = " + gameId;
  435. IDbConnection conn = new SqliteConnection(databaseUrl);
  436. conn.Open();
  437. IDbCommand cmd = conn.CreateCommand();
  438. cmd.CommandText = sql;
  439. IDataReader reader = cmd.ExecuteReader();
  440. while (reader.Read()) {
  441. this.gameMode = reader.GetString(0);
  442. }
  443. reader.Close();
  444. cmd.Dispose();
  445. conn.Close();
  446. }
  447. return this.gameMode;
  448. }
  449. public void LinkPlayersToLocalGame(List<string> playerNames, int gameId) {
  450. IDbConnection conn = new SqliteConnection(databaseUrl);
  451. conn.Open();
  452. string questionSql = "SELECT id FROM questions order by random() limit 1";
  453. IDbCommand cmd = conn.CreateCommand();
  454. cmd.CommandText = questionSql;
  455. IDataReader reader = cmd.ExecuteReader();
  456. int questionId = -1;
  457. while (reader.Read()) {
  458. questionId = reader.GetInt32(0);
  459. }
  460. List<int> l = new List<int>();
  461. l.Add(questionId);
  462. foreach (string player in playerNames) {
  463. string sql = "SELECT id FROM localUsers WHERE name = '" + player + "'";
  464. int playerId;
  465. cmd = conn.CreateCommand();
  466. cmd.CommandText = sql;
  467. reader = cmd.ExecuteReader();
  468. if (reader.Read()) {
  469. playerId = reader.GetInt32(0);
  470. } else {
  471. reader.Close();
  472. sql = "INSERT INTO localUsers (name) VALUES ('" + player + "')";
  473. cmd.CommandText = sql;
  474. cmd.ExecuteNonQuery();
  475. cmd.CommandText = "SELECT last_insert_rowid()";
  476. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  477. playerId = (int)lastInsert64;
  478. }
  479. cmd.Dispose();
  480. reader.Close();
  481. LinkPlayerToGame(playerId, gameId);
  482. SavePlayersQuestion(l, player, gameId, "Local");
  483. }
  484. IDbCommand cmd2 = conn.CreateCommand();
  485. cmd2.CommandText = "UPDATE game SET currentPlayer = '" + playerNames[0] + "' WHERE id = " + gameId;
  486. cmd2.ExecuteNonQuery();
  487. cmd2.Dispose();
  488. conn.Close();
  489. }
  490. private void LinkPlayerToGame(int playerId, int gameId) {
  491. string sql = "INSERT INTO localGamePlayers (gameId, playerId) VALUES (" + gameId + ", " + playerId + ")";
  492. SqliteConnection conn2 = new SqliteConnection(databaseUrl);
  493. conn2.Open();
  494. IDbCommand cmd = conn2.CreateCommand();
  495. cmd.CommandText = sql;
  496. cmd.ExecuteNonQuery();
  497. cmd.Dispose();
  498. conn2.Close();
  499. }
  500. internal int GetWinCondition(int gameId, string gameMode) {
  501. if (gameMode.Equals("Online")) {
  502. return OnlineDatabase.Instance.GetWinCondition(gameId);
  503. }
  504. if (winAmount == -1) {
  505. string sql = "SELECT winNumber FROM game WHERE id = " + gameId;
  506. IDbConnection conn = new SqliteConnection(databaseUrl);
  507. conn.Open();
  508. IDbCommand cmd = conn.CreateCommand();
  509. cmd.CommandText = sql;
  510. IDataReader reader = cmd.ExecuteReader();
  511. while (reader.Read()) {
  512. this.winAmount = reader.GetInt32(0);
  513. }
  514. reader.Close();
  515. cmd.Dispose();
  516. conn.Close();
  517. }
  518. return this.winAmount;
  519. }
  520. public int SetupNewLocalGame(int winNumber, int numberOfPlayers, int questionTimer) {
  521. string sql = "INSERT INTO game (winNumber, numberOfPlayers, answerTimer, gameMode, startedDate) VALUES (" + winNumber + "," + numberOfPlayers + "," + questionTimer + ", 'Local', DATE())";
  522. IDbConnection conn = new SqliteConnection(databaseUrl);
  523. conn.Open();
  524. IDbCommand cmd = conn.CreateCommand();
  525. cmd.CommandText = sql;
  526. int status = cmd.ExecuteNonQuery();
  527. cmd.CommandText = "SELECT last_insert_rowid()";
  528. Int64 lastInsert64 = (Int64)cmd.ExecuteScalar();
  529. return (int)lastInsert64;
  530. }
  531. public NewQuestion GetNewQuestion(List<int> userAnsweredQuestions, string userName, string gameMode) {
  532. if (gameMode.Equals("Online")) {
  533. return OnlineDatabase.Instance.GetNewQuestion(userAnsweredQuestions, userName);
  534. }
  535. int gameId = GameObject.Find("GameManager").GetComponent<GameManagerScript>().GameId;
  536. Color32 questionCategoryColor = new Color32(0, 0, 20, 20);
  537. if (connectionType == null) {
  538. SetLocalOrOnline(GetGameMode(gameId));
  539. }
  540. if (connectionType == "Local") {
  541. IDbConnection conn = new SqliteConnection(databaseUrl);
  542. conn.Open();
  543. IDbCommand cmd = conn.CreateCommand();
  544. string answeredIds = String.Join(",", userAnsweredQuestions);
  545. string sql = "SELECT questions.id, question, answer, categoryId as category, name, category.R, category.G, category.B, category.A FROM questions INNER JOIN questionToCategory ON questions.id = questionToCategory.questionId INNER JOIN category on category.id = questionToCategory.categoryId WHERE questions.id NOT IN (" + answeredIds + ") AND questions.id NOT IN (SELECT questionId FROM questionsInGame WHERE gameId = " + gameId + " AND userId = (SELECT id from localUsers WHERE name = '" + userName + "')) ORDER BY RANDOM() limit 1";
  546. cmd.CommandText = sql;
  547. IDataReader reader = cmd.ExecuteReader();
  548. int id = -1;
  549. while (reader.Read()) {
  550. id = reader.GetInt32(0);
  551. string question = reader.GetString(1);
  552. int answer = reader.GetInt32(2);
  553. int catergoryId = reader.GetInt32(3);
  554. string categoryName = reader.GetString(4);
  555. idString = id.ToString();
  556. questionString = question;
  557. categoryString = catergoryId.ToString();
  558. answerString = answer.ToString();
  559. byte r = (byte)reader.GetInt32(5);
  560. byte g = (byte)reader.GetInt32(6);
  561. byte b = (byte)reader.GetInt32(7);
  562. byte a = (byte)reader.GetInt32(8);
  563. questionCategoryColor = new Color32(r, g, b, a);
  564. }
  565. reader.Close();
  566. string saveSentQuestionSql = "INSERT INTO questionsInGame (gameId, questionId, userId) VALUES (" + gameId + ", " + id + ", (SELECT id FROM localUsers WHERE name = '" + userName + "'))";
  567. cmd.CommandText = saveSentQuestionSql;
  568. cmd.ExecuteNonQuery();
  569. cmd.Dispose();
  570. conn.Close();
  571. } else { // Connect Through db
  572. Debug.Log("Online Call");
  573. StartCoroutine(GetQuestionData(false));
  574. }
  575. NewQuestion q = NewQuestion.Instance();
  576. q.questionString = questionString;
  577. q.answerString = answerString;
  578. q.categoryString = categoryString;
  579. q.idString = idString;
  580. q.SetQuestionCategoryColor(questionCategoryColor);
  581. return q;
  582. }
  583. public void SavePlayersQuestion(List<int> questionsToSave, string playerNameValue, int gameId, string gameMode) {
  584. if (gameMode.Equals("Online")) {
  585. OnlineDatabase.Instance.SavePlayersQuestion(questionsToSave, playerNameValue, gameId);
  586. } else {
  587. SetLocalOrOnline(gameMode);
  588. string values = "";
  589. foreach (int questionId in questionsToSave) {
  590. values += "(" + playerNameValue + "," + questionId + "," + gameId + "),";
  591. }
  592. values = values.Substring(0, values.Length - 1);
  593. string sql = "INSERT OR IGNORE INTO usersLockedQuestions (playerName, questionId, gameId) VALUES " + values;
  594. IDbConnection conn = new SqliteConnection(databaseUrl);
  595. conn.Open();
  596. IDbCommand cmd = conn.CreateCommand();
  597. cmd.CommandText = sql;
  598. cmd.ExecuteReader();
  599. cmd.Dispose();
  600. conn.Close();
  601. }
  602. }
  603. public List<QuestionCard> GetPlayerQuestions(int gameId, string playerNameValue, string gameMode) {
  604. if (gameMode.Equals("Online")) {
  605. return OnlineDatabase.Instance.GetPlayerQuestions(gameId, playerNameValue);
  606. }
  607. if (databaseUrl == null) {
  608. SetLocalOrOnline(GetGameMode(gameId));
  609. }
  610. List<QuestionCard> questions = new List<QuestionCard>();
  611. if (connectionType.Equals("Local")) {
  612. string sql = "SELECT * FROM questions inner join questionToCategory on questions.id = questionToCategory.questionId INNER JOIN category ON category.id = questionToCategory.categoryId WHERE questions.id IN ( SELECT questionId FROM usersLockedQuestions WHERE gameId = " + gameId + " AND playerName = '" + playerNameValue + "') ORDER BY answer ASC";
  613. IDbConnection conn = new SqliteConnection(databaseUrl);
  614. conn.Open();
  615. IDbCommand cmd = conn.CreateCommand();
  616. cmd.CommandText = sql;
  617. IDataReader reader = cmd.ExecuteReader();
  618. while (reader.Read()) {
  619. GameObject question = Instantiate(questionCardPrefab, new Vector2(0, 0), Quaternion.identity) as GameObject;
  620. QuestionCard q = question.GetComponent<QuestionCard>();
  621. q.SetAnswerText(reader.GetInt32(2).ToString());
  622. q.SetQuestionText(reader.GetString(1));
  623. q.idString = reader.GetInt32(0).ToString();
  624. Color32 questionCategoryColor = new Color32((byte)reader.GetInt32(7), (byte)reader.GetInt32(8), (byte)reader.GetInt32(9), (byte)reader.GetInt32(10));
  625. q.SetQuestionCategoryColor(questionCategoryColor);
  626. questions.Add(q);
  627. }
  628. cmd.Dispose();
  629. conn.Close();
  630. }
  631. return questions;
  632. }
  633. private IEnumerator GetQuestionData(bool showAnswer) {
  634. UnityWebRequest www = UnityWebRequest.Get("nordh.xyz/narKampen/dbFiles/Question.php");
  635. yield return www.SendWebRequest();
  636. if (www.isNetworkError || www.isHttpError) {
  637. Debug.Log(www.error);
  638. } else {
  639. while (!www.isDone) {
  640. yield return null;
  641. }
  642. // Show result
  643. string jsonData = www.downloadHandler.text;
  644. jsonData = "{\"questionsList\" : [ " + jsonData + " ]}";
  645. Questions qe = new Questions();
  646. JsonUtility.FromJsonOverwrite(jsonData, qe);
  647. questionString = qe.questionsList[0].question;
  648. answerString = qe.questionsList[0].answer;
  649. idString = qe.questionsList[0].id;
  650. categoryString = qe.questionsList[0].category;
  651. }
  652. }
  653. }