SerializableJSONState.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-09-15
  6. * Changed: 2020-09-17
  7. *
  8. * */
  9. #include "SerializableJSONState.hpp"
  10. #include "SerializableJSONStateConnection.hpp"
  11. ls_std::SerializableJSONState::SerializableJSONState(std::shared_ptr<State> _value) :
  12. Class("SerializableJSONState"),
  13. value(std::move(_value))
  14. {}
  15. ls_std::byte_field ls_std::SerializableJSONState::marshal()
  16. {
  17. this->_update();
  18. return this->jsonObject.dump();
  19. }
  20. void ls_std::SerializableJSONState::unmarshal(const ls_std::byte_field &_data)
  21. {
  22. this->jsonObject = nlohmann::json::parse(_data);
  23. this->_unmarshalStateConnections();
  24. this->value->setId(this->jsonObject["id"]);
  25. }
  26. void ls_std::SerializableJSONState::setValue(std::shared_ptr<State> _value)
  27. {
  28. this->value = std::move(_value);
  29. }
  30. void ls_std::SerializableJSONState::_unmarshalExistingStateConnection(nlohmann::json _jsonObject)
  31. {
  32. std::shared_ptr<ls_std::StateConnection> stateConnection = this->value->getConnectedStates().at(_jsonObject["connectionId"]);
  33. stateConnection->updatePassCondition(_jsonObject["condition"]);
  34. stateConnection->setStateId(_jsonObject["stateId"]);
  35. }
  36. void ls_std::SerializableJSONState::_unmarshalNewStateConnection(nlohmann::json _jsonObject)
  37. {
  38. std::shared_ptr<ls_std::StateConnection> stateConnection = std::make_shared<ls_std::StateConnection>(_jsonObject["connectionId"], _jsonObject["stateId"]);
  39. stateConnection->updatePassCondition(_jsonObject["condition"]);
  40. this->value->addStateConnection(stateConnection);
  41. }
  42. void ls_std::SerializableJSONState::_unmarshalStateConnections()
  43. {
  44. for(const auto& connectedState : this->jsonObject["connectedStates"]) {
  45. if(this->value->hasConnection(connectedState["connectionId"])) {
  46. this->_unmarshalExistingStateConnection(connectedState);
  47. }
  48. else {
  49. this->_unmarshalNewStateConnection(connectedState);
  50. }
  51. }
  52. }
  53. void ls_std::SerializableJSONState::_update()
  54. {
  55. this->_updateStateConnections();
  56. this->jsonObject["id"] = this->value->getId();
  57. }
  58. void ls_std::SerializableJSONState::_updateStateConnections()
  59. {
  60. std::string jsonString {};
  61. for(const auto& connection : this->value->getConnectedStates()) {
  62. jsonString = ls_std::SerializableJSONStateConnection{connection.second}.marshal();
  63. this->jsonObject["connectedStates"][connection.first] = nlohmann::json::parse(jsonString);
  64. }
  65. }