ApiHandler.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. }
  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.Picture:
  43. if (o["selected"].ToObject<bool>() == true)
  44. {
  45. Debug.WriteLine("Selected player taking picture");
  46. App.Game.Selected = true;
  47. App.Navigate(typeof(PhotoView));
  48. }
  49. else
  50. App.Navigate(typeof(WaitingView));
  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 GameFound()
  63. {
  64. throw new NotImplementedException();
  65. if (OnGameFound == null) return;
  66. OnGameFound(this, new EventArgs());
  67. }
  68. public JObject Message(Command c, string msg)
  69. {
  70. return JObject.FromObject(new
  71. {
  72. command = c.ToString(),
  73. msg = msg
  74. });
  75. }
  76. //API stuff
  77. public async Task<bool> SearchGame()
  78. {
  79. JObject obj = JObject.FromObject(new
  80. {
  81. command = Command.Name.ToString(),
  82. name = Settings.Username
  83. });
  84. Debug.WriteLine(obj.ToString(Formatting.None));
  85. await App.Network.Write(obj.ToString(Formatting.None));
  86. return true;
  87. }
  88. }
  89. }