//
//  VeplayerView.m
//

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

@implementation VeplayerView

- (instancetype)init {
  self = [super init];
  if (self != nil) {
    self.clipsToBounds = YES;
  }
  NSLog(@"[View] create VeplayerView success");
  return self;
}

- (void)setViewId:(NSString *)viewId {
  if ([_viewId isEqualToString:viewId]) {
    return;
  }

  // 先注销旧的 viewId
  if (_viewId) {
    [VolcViewManager unregisterView:_viewId];
  }

  // 清理旧的视图
  [self removeAllSubviews];

  _viewId = [viewId copy]; // 使用 copy 来确保字符串的所有权
  self.hasRegister = TRUE;
  self.accessibilityLabel =
      [NSString stringWithFormat:@"VeplayerView@%@", viewId];

  [self emitLoaded];
}

- (void)setOnPlayerViewLoad:(RCTBubblingEventBlock)onLoad {
  _onLoad = onLoad;

  [self emitLoaded];
}

- (void)emitLoaded {
  if (_onLoad != nil && _hasRegister == TRUE) {
    _onLoad(@{});
  }
}

- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index {
  // 清理旧的视图
  [self removeAllSubviews];
  // 添加弱引用避免循环引用
  __weak typeof(self) weakSelf = self;
  dispatch_async(dispatch_get_main_queue(), ^{
    __strong typeof(weakSelf) strongSelf = weakSelf;
    if (!strongSelf)
      return;

    [super insertSubview:view atIndex:index];
    [strongSelf setSubViewLayout:view];
  });
}

- (void)addSubview:(UIView *)view {
  dispatch_async(dispatch_get_main_queue(), ^{
    [super addSubview:view];
    [self setSubViewLayout:view];
  });
}

// 设置 Auto Layout，确保 subView 始终匹配 view 尺寸
- (void)setSubViewLayout:(UIView *)view {
  // 先移除旧的约束
  [self removeConstraintsWithView:view];

  // 确保视图已经添加到父视图中
  if (view.superview != self) {
    [super addSubview:view];
  }

  view.translatesAutoresizingMaskIntoConstraints = YES;
  view.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  view.frame = self.bounds;
}

- (void)removeConstraintsWithView:(UIView *)view {
  NSArray *constraints = self.constraints;
  for (NSLayoutConstraint *constraint in constraints) {
    if (constraint.firstItem == view || constraint.secondItem == view) {
      [self removeConstraint:constraint];
    }
  }
}

- (void)dealloc {
  // 在主线程执行清理
  if ([NSThread isMainThread]) {
    [self cleanup];
  } else {
    dispatch_sync(dispatch_get_main_queue(), ^{
      [self cleanup];
    });
  }

  // 清理其他资源
  _viewId = nil;
  _onLoad = nil;
}

- (void)removeSubview:(UIView *)view {
  if (view.superview == self) {
    dispatch_async(dispatch_get_main_queue(), ^{
      [view removeFromSuperview];
    });
  }
}

- (void)cleanup {
  // 如果有 viewId，需要注销
  if (_viewId) {
    [VolcViewManager unregisterView:_viewId];
  }

  // 移除所有子视图
  [self removeAllSubviews];

  // 清理事件回调
  _onLoad = nil;
  self.hasRegister = NO;

  // 移除所有约束
  [self removeConstraints:self.constraints];
}

- (void)removeAllSubviews {
  if ([NSThread isMainThread]) {
    [self doRemoveAllSubviews];
  } else {
    dispatch_async(dispatch_get_main_queue(), ^{
      [self doRemoveAllSubviews];
    });
  }
}

- (void)doRemoveAllSubviews {
  NSArray *subviews = [self.subviews copy];
  for (UIView *view in subviews) {
    [view removeFromSuperview];
  }
}

@end
