// Copyright © 2022 BytePlusRTC All rights reserved.
// SPDX-License-Identifier: MIT

//
//  VertcView.m
//

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

@implementation VertcView

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

- (void) setViewId:(NSString *)viewId {
  if ([_viewId isEqualToString:viewId]) {
    return;
  }
  
  _viewId = viewId;
  self.hasRegister = TRUE;
  self.accessibilityLabel = [NSString stringWithFormat:@"VertcView@%@", 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 {  
  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];
  });
}

- (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
