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

#include "JHybridNitroImageViewStateUpdater.hpp"
#include "views/HybridNitroImageViewComponent.hpp"
#include <NitroModules/NitroDefines.hpp>
#include <react/fabric/StateWrapperImpl.h>

namespace margelo::nitro::image::views {

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

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

  // 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 HybridNitroImageViewState& data = concreteState->getData();
  const std::shared_ptr<HybridNitroImageViewProps>& props = data.getProps();
  if (props == nullptr) [[unlikely]] {
    // Props aren't set yet!
    throw std::runtime_error("HybridNitroImageViewState's data doesn't contain any props!");
  }

  // Update all props if they are dirty
  if (props->image.isDirty) {
    hybridView->setImage(props->image.value);
    props->image.isDirty = false;
  }
  if (props->resizeMode.isDirty) {
    hybridView->setResizeMode(props->resizeMode.value);
    props->resizeMode.isDirty = false;
  }
  if (props->recyclingKey.isDirty) {
    hybridView->setRecyclingKey(props->recyclingKey.value);
    props->recyclingKey.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::image::views
