ApiHandler.cs 3.1 KB

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