ApiHandler.cs 3.2 KB

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