ApiHandler.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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("Reached HandleMessage in API");
  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. default:
  42. //Do nothing
  43. break;
  44. }
  45. }
  46. private void PlayerJoined(string username)
  47. {
  48. //Event will be handled by the game manager
  49. App.Game.AddPlayer(username);
  50. }
  51. private void GameFound()
  52. {
  53. throw new NotImplementedException();
  54. if (OnGameFound == null) return;
  55. OnGameFound(this, new EventArgs());
  56. }
  57. public JObject Message(Command c, string msg)
  58. {
  59. return JObject.FromObject(new
  60. {
  61. command = c.ToString(),
  62. msg = msg
  63. });
  64. }
  65. //API stuff
  66. public async Task<bool> SearchGame()
  67. {
  68. JObject obj = JObject.FromObject(new
  69. {
  70. command = Command.Name.ToString(),
  71. name = Settings.Username
  72. });
  73. Debug.WriteLine(obj.ToString(Formatting.None));
  74. await App.Network.Write(obj.ToString(Formatting.None));
  75. return true;
  76. }
  77. }
  78. }