///
/// JHybridOmniViewStateUpdater.cpp
/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
/// https://github.com/mrousavy/nitro
/// Copyright © Marc Rousavy @ Margelo
///

#include "JHybridOmniViewStateUpdater.hpp"
#include "views/HybridOmniViewComponent.hpp"
#include <NitroModules/NitroDefines.hpp>
#include <react/fabric/StateWrapperImpl.h>

namespace margelo::nitro::omni::views {

using namespace facebook;
using ConcreteStateData = react::ConcreteState<HybridOmniViewState>;

void JHybridOmniViewStateUpdater::updateViewProps(jni::alias_ref<jni::JClass> /* class */,
                                           jni::alias_ref<JHybridOmniViewSpec::JavaPart> javaView,
                                           jni::alias_ref<JStateWrapper::javaobject> stateWrapperInterface) {
  std::shared_ptr<JHybridOmniViewSpec> hybridView = javaView->getJHybridOmniViewSpec();

  // Get concrete StateWrapperImpl from passed StateWrapper interface object
  jobject rawStateWrapper = stateWrapperInterface.get();
  if (!stateWrapperInterface->isInstanceOf(react::StateWrapperImpl::javaClassStatic())) [[unlikely]] {
      throw std::runtime_error("StateWrapper is not a StateWrapperImpl");
  }
  auto stateWrapper = jni::alias_ref<react::StateWrapperImpl::javaobject>{
            static_cast<react::StateWrapperImpl::javaobject>(rawStateWrapper)};
  std::shared_ptr<const react::State> state = stateWrapper->cthis()->getState();
  auto concreteState = std::static_pointer_cast<const ConcreteStateData>(state);
  const HybridOmniViewState& data = concreteState->getData();
  const std::shared_ptr<HybridOmniViewProps>& props = data.getProps();
  if (props == nullptr) [[unlikely]] {
    // Props aren't set yet!
    throw std::runtime_error("HybridOmniViewState's data doesn't contain any props!");
  }

  // Update all props if they are dirty
  if (props->player.isDirty) {
    hybridView->setPlayer(props->player.value);
    props->player.isDirty = false;
  }
  if (props->autoplay.isDirty) {
    hybridView->setAutoplay(props->autoplay.value);
    props->autoplay.isDirty = false;
  }
  if (props->autoPip.isDirty) {
    hybridView->setAutoPip(props->autoPip.value);
    props->autoPip.isDirty = false;
  }
  if (props->subtitleAssets.isDirty) {
    hybridView->setSubtitleAssets(props->subtitleAssets.value);
    props->subtitleAssets.isDirty = false;
  }

  // Update hybridRef if it changed
  if (props->hybridRef.isDirty) {
    // hybridRef changed - call it with new this
    const auto& maybeFunc = props->hybridRef.value;
    if (maybeFunc.has_value()) {
      maybeFunc.value()(hybridView);
    }
    props->hybridRef.isDirty = false;
  }
}

} // namespace margelo::nitro::omni::views
