Database.cs 26 KB

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