#import "PlayerMultiObserver.h"
#import <TTSDKFramework/TTSDKFramework.h>

@interface PlayerMultiObserver ()
@property(nonatomic, strong) NSMutableDictionary *observerDict;
@property(nonatomic, strong) dispatch_queue_t observerQueue;
@property(nonatomic, strong) TTVideoEngine *player;
@end

@implementation PlayerMultiObserver

- (instancetype)initWithPlayer:(TTVideoEngine *)player {
  self = [super init];
  if (self) {
    _observerDict = [NSMutableDictionary dictionary];
    _observerQueue = dispatch_queue_create("com.veplayer.player.multiobserver", DISPATCH_QUEUE_SERIAL);
    _player = player;
    player.resolutionDelegate = self;
  }
  return self;
}

- (void)setupPlayer:(TTVideoEngine *)player {
  if (self.player) {
    self.player.resolutionDelegate = nil;
    [self clearObservers];
  }
  self.player = player;
  player.resolutionDelegate = self;
}

- (void)addObserver:(NSString *)observerId
           observer:(id<TTVideoEngineResolutionDelegate>)observer {
  if (!observer || !observerId) {
    return;
  }

  dispatch_sync(self.observerQueue, ^{
    [self.observerDict setObject:observer forKey:observerId];
  });
}

- (void)removeObserver:(NSString *)observerId {
  if (!observerId) {
    return;
  }

  dispatch_sync(self.observerQueue, ^{
    [self.observerDict removeObjectForKey:observerId];
  });
}

- (NSArray *)getObservers {
  __block NSArray *result = nil;
  dispatch_sync(self.observerQueue, ^{
    result = [self.observerDict allValues];
  });
  return result;
}

- (void)clearObservers {
  dispatch_sync(self.observerQueue, ^{
    [self.observerDict removeAllObjects];
  });
}

#pragma mark - TTVideoEngineResolutionDelegate

- (void)videoSizeDidChange:(TTVideoEngine *)videoEngine videoWidth:(NSInteger)videoWidth videoHeight:(NSInteger)videoHeight {
  dispatch_sync(self.observerQueue, ^{
    for (id<TTVideoEngineResolutionDelegate> observer in [self.observerDict allValues]) {
      if ([observer respondsToSelector:@selector(videoSizeDidChange:videoWidth:videoHeight:)]) {
        [observer videoSizeDidChange:videoEngine videoWidth:videoWidth videoHeight:videoHeight];
      }
    }
  });
}

@end
