ApiHandler.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. }
  25. public ApiHandler()
  26. {
  27. }
  28. public void HandleMessage(JObject o)
  29. {
  30. Debug.WriteLine(o.ToString());
  31. Command c = (Command)Enum.Parse(typeof(Command), o["command"].ToString());
  32. switch (c)
  33. {
  34. case Command.GameFound:
  35. GameFound();
  36. break;
  37. case Command.PlayerJoined:
  38. Debug.WriteLine("Played joined");
  39. PlayerJoined(o[Command.PlayerJoined.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. }
  47. break;
  48. default:
  49. //Do nothing
  50. break;
  51. }
  52. }
  53. private void PlayerJoined(string username)
  54. {
  55. //Event will be handled by the game manager
  56. App.Game.AddPlayer(username);
  57. }
  58. private void GameFound()
  59. {
  60. throw new NotImplementedException();
  61. if (OnGameFound == null) return;
  62. OnGameFound(this, new EventArgs());
  63. }
  64. public JObject Message(Command c, string msg)
  65. {
  66. return JObject.FromObject(new
  67. {
  68. command = c.ToString(),
  69. msg = msg
  70. });
  71. }
  72. //API stuff
  73. public async Task<bool> SearchGame()
  74. {
  75. JObject obj = JObject.FromObject(new
  76. {
  77. command = Command.Name.ToString(),
  78. name = Settings.Username
  79. });
  80. Debug.WriteLine(obj.ToString(Formatting.None));
  81. await App.Network.Write(obj.ToString(Formatting.None));
  82. return true;
  83. }
  84. }
  85. }