#import "VeplayerSubtitle+TTVideoEngineSubProtocol.h"

@interface VeplayerTTVideoEngineSubProtocolImpl ()

@property(nonatomic, assign) NSInteger languageId;
@property(nonatomic, copy) NSString *urlString;
@property(nonatomic, copy) NSString *format;
@property(nonatomic, assign) NSInteger subtitleId;
@property(nonatomic, copy) NSString *cacheKey;

@end

@implementation VeplayerTTVideoEngineSubProtocolImpl

static NSInteger _defaultLanguageId = -1;

+ (instancetype)createWithJson:(NSDictionary *)json {
  return [[VeplayerTTVideoEngineSubProtocolImpl alloc] initWithJson:json];
}

+ (id<TTVideoEngineSubProtocol>)getSubtitleProtocolWithJson:
    (NSDictionary *)json {

  VeplayerTTVideoEngineSubProtocolImpl *subtitleProtocol =
      [[VeplayerTTVideoEngineSubProtocolImpl alloc] initWithJson:json];

  return subtitleProtocol;
}

- initWithJson:(NSDictionary *)json {
  self = [super init];
  if (self != nil) {
    _languageId = [[json objectForKey:@"language_id"] integerValue];
    _urlString = [json objectForKey:@"url"];
    _format = [json objectForKey:@"format"];
    _subtitleId = [[json objectForKey:@"sub_id"] integerValue];
    _cacheKey = [json objectForKey:@"cache_key"];
  }
  return self;
}

+ (void)setDefaultSubLanguageId:(NSInteger)languageId {
  _defaultLanguageId = languageId;
}

+ (void)setupPreloadSubtitleBlockForVidSource:
    (TTVideoEngineVidSource *)vidSource {
  if (!vidSource) {
    return;
  }

  vidSource.preloadSubtitleModelBlock = ^id<TTVideoEngineSubProtocol> _Nonnull(
      NSArray<id<TTVideoEngineSubProtocol>> *_Nonnull subModels) {
    // If default language ID is set, select subtitle based on languageId
    if (_defaultLanguageId != -1 && subModels && subModels.count > 0) {
      for (id<TTVideoEngineSubProtocol> subtitle in subModels) {
        if ([subtitle respondsToSelector:@selector(languageId)] &&
            [subtitle languageId] == _defaultLanguageId) {
          return subtitle;
        }
      }
      // If no matching language ID is found, return the first subtitle
      return [subModels firstObject];
    }

    // If no default language ID is set, return the first subtitle
    if (subModels && subModels.count > 0) {
      return [subModels firstObject];
    }
    return nil;
  };
}

@end
