ApiHandler.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using YJMPD_UWP.Helpers;
  10. namespace YJMPD_UWP.Model
  11. {
  12. public class ApiHandler
  13. {
  14. public delegate void OnGameFoundHandler(object sender, EventArgs e);
  15. public event OnGameFoundHandler OnGameFound;
  16. public enum Command
  17. {
  18. Hi,
  19. Name,
  20. Picture,
  21. Msg,
  22. GameFound,
  23. PlayerJoined,
  24. PlayerRemoved
  25. }
  26. public ApiHandler()
  27. {
  28. }
  29. public void HandleMessage(JObject o)
  30. {
  31. Debug.WriteLine(o.ToString());
  32. Command c = (Command)Enum.Parse(typeof(Command), o["command"].ToString());
  33. switch (c)
  34. {
  35. case Command.GameFound:
  36. GameFound();
  37. break;
  38. case Command.PlayerJoined:
  39. Debug.WriteLine("Played joined");
  40. PlayerJoined(o[Command.PlayerJoined.ToString()].ToString());
  41. break;
  42. case Command.PlayerRemoved:
  43. Debug.WriteLine("Played removed");
  44. PlayerRemoved(o[Command.PlayerRemoved.ToString()].ToString());
  45. break;
  46. case Command.Picture:
  47. if (o["selected"].ToObject<bool>() == true)
  48. {
  49. Debug.WriteLine("Selected player taking picture");
  50. App.Game.Selected = true;
  51. }
  52. break;
  53. default:
  54. //Do nothing
  55. break;
  56. }
  57. }
  58. private void PlayerJoined(string username)
  59. {
  60. //Event will be handled by the game manager
  61. App.Game.AddPlayer(username);
  62. }
  63. private void PlayerRemoved(string username)
  64. {
  65. //Event will be handled by the game manager
  66. App.Game.RemovePlayer(username);
  67. }
  68. private void GameFound()
  69. {
  70. throw new NotImplementedException();
  71. if (OnGameFound == null) return;
  72. OnGameFound(this, new EventArgs());
  73. }
  74. public JObject Message(Command c, string msg)
  75. {
  76. return JObject.FromObject(new
  77. {
  78. command = c.ToString(),
  79. msg = msg
  80. });
  81. }
  82. //API stuff
  83. public async Task<bool> SearchGame()
  84. {
  85. JObject obj = JObject.FromObject(new
  86. {
  87. command = Command.Name.ToString(),
  88. name = Settings.Username
  89. });
  90. Debug.WriteLine(obj.ToString(Formatting.None));
  91. await App.Network.Write(obj.ToString(Formatting.None));
  92. return true;
  93. }
  94. }
  95. }