//
//  VeUIView.m
//  rn
//
//  Created by ByteDance on 2024/5/20.
//

#import <Foundation/Foundation.h>
#import "VeLivePullView.h"

@implementation VeLivePullUIView

- (instancetype) init {
  self = [super init];
  if (self != nil) {
    self.clipsToBounds = YES;
  }
  return self;
}

- (void) setViewId:(NSString *)viewId {
  if ([_viewId isEqualToString:viewId]) {
    return;
  }
  
  _viewId = viewId;
  self.hasRegister = TRUE;
  self.accessibilityLabel = [NSString stringWithFormat:@"VeLivePullUIView@%@", viewId];

  [self emitLoaded];
}

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

  [self emitLoaded];
}

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

- (void) insertSubview:(UIView *)view atIndex:(NSInteger)index {
//  NSLog(@"insert playview, self bounds=%f x %f", self.bounds.size.width, self.bounds.size.height);
//  NSLog(@"insert playview, view frame=%f x %f", view.frame.size.width, view.frame.size.height);
  
  dispatch_async(dispatch_get_main_queue(), ^{
    [super insertSubview:view atIndex:index];
    [self 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 {
  view.translatesAutoresizingMaskIntoConstraints = NO;
  [NSLayoutConstraint activateConstraints:@[
    [view.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
    [view.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
    [view.topAnchor constraintEqualToAnchor:self.topAnchor],
    [view.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]
  ]];
}

@end
