#import "TBLRNTPluginView.h"
#import "TBLRNTClassicPage.h"
#import "TBLRNTClassicPagesMap.h"


#import <react/renderer/components/RNTaboolaReactNativePlugin4xViewSpec/ComponentDescriptors.h>
#import <react/renderer/components/RNTaboolaReactNativePlugin4xViewSpec/EventEmitters.h>
#import <react/renderer/components/RNTaboolaReactNativePlugin4xViewSpec/Props.h>
#import <react/renderer/components/RNTaboolaReactNativePlugin4xViewSpec/RCTComponentViewHelpers.h>


#import "RCTFabricComponentsPlugins.h"
#import "TBLRNTConstants.h"
#import "TBLRNTUtils.h"

using namespace facebook::react;

@interface TBLRNTPluginView () <RCTTBLRNTPluginViewViewProtocol>

@end

@implementation TBLRNTPluginView

+ (ComponentDescriptorProvider)componentDescriptorProvider {
  return concreteComponentDescriptorProvider<
      TBLRNTPluginViewComponentDescriptor>();
}

// Disable view recycling optimization
// Android has this feature disabled by default in the New Architecture
// ref - https://www.linkedin.com/pulse/react-natives-new-architecture-tricky-parts-12-software-mansion-cbvpf/
+ (BOOL)shouldBeRecycled {
  return NO;
}

- (instancetype)initWithFrame:(CGRect)frame {
  if (self = [super initWithFrame:frame]) {
    static const auto defaultProps =
        std::make_shared<const TBLRNTPluginViewProps>();
    _props = defaultProps;
  }
  return self;
}

- (void)updateProps:(Props::Shared const &)props
           oldProps:(Props::Shared const &)oldProps {
  const auto &oldViewProps =
      *std::static_pointer_cast<TBLRNTPluginViewProps const>(_props);
  const auto &newViewProps =
      *std::static_pointer_cast<TBLRNTPluginViewProps const>(props);

  NSString *unitId =
      [NSString stringWithUTF8String:newViewProps.initValues.unitId.c_str()];
  if (!unitId || [unitId isEqualToString:@""]) {
    NSLog(@"[TBLRNTPluginView] Error: UnitId is nil or empty");
    return;
  }

  NSString *pageId =
      [NSString stringWithUTF8String:newViewProps.initValues.pageId.c_str()];
  if (!pageId || [pageId isEqualToString:@""]) {
    NSLog(@"[TBLRNTPluginView] Error: PageId is nil or empty");
    return;
  }

  TBLRNTClassicPage *classicPage = [TBLRNTUtils getClassicPageForPageId:pageId];
  if (!classicPage) {
    NSLog(@"[TBLRNTPluginView] Error: %@", kPageNotFoundErrorMsg);
    return;
  }

  TBLClassicUnit *tblClassicUnit = [classicPage getClassicUnit:unitId];
  if (!tblClassicUnit) {
    NSLog(@"[TBLRNTPluginView] Error: %@", kTBLClassicUnitNotFoundErrorMsg);
    return;
  }

  // Set content view if not already set
  if (!self.contentView) {
    self.contentView = tblClassicUnit;
  }

  [super updateProps:props oldProps:oldProps];
}

Class<RCTComponentViewProtocol> TaboolaReactNativePluginViewCls(void) {
  return TBLRNTPluginView.class;
}

@end
