//
//  VeUIView.m
//  rn
//
//  Created by ByteDance on 2024/3/27.
//

#import "VeplayerView.h"
#import "VolcApiEngine/VolcViewManager.h"
#import <Foundation/Foundation.h>
#import <React/RCTUIManager.h>
#import <React/RCTViewManager.h>

@interface VeplayerViewManager : RCTViewManager

@end

@implementation VeplayerViewManager

+ (BOOL)requiresMainQueueSetup {
  return YES;
}

RCT_EXPORT_MODULE(VeplayerView)

// export events
RCT_EXPORT_VIEW_PROPERTY(onPlayerViewLoad, RCTBubblingEventBlock)

// export events
RCT_CUSTOM_VIEW_PROPERTY(viewId, NSString, VeplayerView) {
  if (json == nil) {
    return;
  }

  // 如果已经注册过，先注销旧的
  if (view.viewId) {
    [VolcViewManager unregisterView:view.viewId];
  }

  NSString *viewId = [RCTConvert NSString:json];
  [view setViewId:viewId];

  // 使用弱引用来避免循环引用
  __weak VeplayerView *weakView = view;
  [VolcViewManager registerView:viewId view:weakView];
  NSLog(@"[View] register view success viewId=%@", viewId);
}

RCT_CUSTOM_VIEW_PROPERTY(kind, NSString, VeplayerView) {
  if (json == nil) {
    return;
  }

  //  NSString *viewKind = [RCTConvert NSString:json];
  //  if ([viewKind isEqualToString:@"UIView"]) {
  //    UIView *sub = [[UIView alloc] init];
  //    [view insertSubview:sub atIndex:0];
  //    NSLog(@"[View] insert view with kind=%@", viewKind);
  //  }
}

- (VeplayerView *)view {
  VeplayerView *view = [[VeplayerView alloc] init];
  return view;
}

- (void)cleanupViews {
  RCTUIManager *uiManager = self.bridge.uiManager;
  id viewRegistry = [uiManager valueForKey:@"viewRegistry"];

  if ([viewRegistry isKindOfClass:[NSMapTable class]]) {
    NSMapTable *registry = (NSMapTable *)viewRegistry;
    NSEnumerator *enumerator = [registry objectEnumerator];
    UIView *view;

    while ((view = [enumerator nextObject])) {
      if ([view isKindOfClass:[VeplayerView class]]) {
        VeplayerView *playerView = (VeplayerView *)view;
        if (playerView.viewId) {
          [VolcViewManager unregisterView:playerView.viewId];
          NSLog(@"[VeplayerViewManager] Unregistered view: %@",
                playerView.viewId);
        }
      }
    }
  }
}

- (void)dealloc {
  [self cleanupViews];
}

@end
