//
//  VeDownloadHelper.m
//  react-native-veplayer
//
//  Created by ByteDance on 2025/2/6.
//  Copyright © 2025 ByteDance. All rights reserved.
//

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

// 前向声明 VolcJsonManager，避免直接导入
@interface VolcJsonManager : NSObject
+ (instancetype)sharedInstance;
- (void)disableJson:(Class)clazz;
- (BOOL)canJsonAble:(id)val;
@end

// 静态变量声明在文件级别
static NSArray<__kindof TTVideoEngineDownloadTask *> *_Nullable s_lastLoadedTasks = nil;
static NSLock *_lastLoadedTasksLock = nil;

@implementation VeDownloadHelper

+ (void)initialize {
  if (self == [VeDownloadHelper class]) {
    _lastLoadedTasksLock = [[NSLock alloc] init];

    // 禁止 TTVideoEngineDownloadTask 及其子类的 JSON 序列化
    // 这样 bridge 会通过实例引用而不是对象序列化来传递任务
    // 避免 MJExtension 遍历 TTVideoEngineDownloadTask 对象时的循环引用问题
    // 循环引用: TTVideoEngineDownloadTask -> TTVideoEngineDownloader -> Tasks -> TTVideoEngineDownloadTask

    // 禁用基类
    Class downloadTaskClass = NSClassFromString(@"TTVideoEngineDownloadTask");
    if (downloadTaskClass) {
      id volcJsonManager = [VolcJsonManager sharedInstance];
      if (volcJsonManager) {
        [volcJsonManager disableJson:downloadTaskClass];
      }
    }

    // 禁用 URLTask 子类
    Class downloadURLTaskClass = NSClassFromString(@"TTVideoEngineDownloadURLTask");
    if (downloadURLTaskClass) {
      id volcJsonManager = [VolcJsonManager sharedInstance];
      if (volcJsonManager) {
        [volcJsonManager disableJson:downloadURLTaskClass];
      }
    }

    // 禁用 VidTask 子类
    Class downloadVidTaskClass = NSClassFromString(@"TTVideoEngineDownloadVidTask");
    if (downloadVidTaskClass) {
      id volcJsonManager = [VolcJsonManager sharedInstance];
      if (volcJsonManager) {
        [volcJsonManager disableJson:downloadVidTaskClass];
      }
    }
  }
}

+ (void)setDownloadDirectoryWithSubdir:(NSString *)subdir {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                       NSUserDomainMask, YES);
  NSString *cacheDir = [paths firstObject];
  NSString *finalDir = cacheDir;
  if (subdir && subdir.length > 0) {
    finalDir = [cacheDir stringByAppendingPathComponent:subdir];
  }
  [[NSFileManager defaultManager] createDirectoryAtPath:finalDir
                            withIntermediateDirectories:YES
                                             attributes:nil
                                                  error:nil];
  [TTVideoEngine ls_localServerConfigure].downloadDirectory = finalDir;
}

+ (void)prepareDownloader {
  [[TTVideoEngineDownloader shareLoader]
      getAllTasksWithCompletionHandler:^(
          NSArray<__kindof TTVideoEngineDownloadTask *> *_Nonnull tasks) {
        // 仅用于触发 SDK 设置 readAllTask=YES；顺带缓存一份最近任务，便于后续
        // JS 侧 loadAllTasks 复用
        [_lastLoadedTasksLock lock];
        s_lastLoadedTasks = [tasks copy];
        [_lastLoadedTasksLock unlock];
      }];
}

+ (void)setMaxCacheCount:(NSInteger)maxCacheCount {
  [TTVideoEngine setGlobalForKey:VEGSKeyPlayerVideoModelMaxCache_NSInteger
                           value:@(maxCacheCount)];
}

+ (void)loadAllTask:(void (^)(BOOL hasTask))completionHandler {
  if (!completionHandler) {
    return;
  }

  [[TTVideoEngineDownloader shareLoader]
      getAllTasksWithCompletionHandler:^(
          NSArray<__kindof TTVideoEngineDownloadTask *> *_Nonnull tasks) {
        [_lastLoadedTasksLock lock];
        s_lastLoadedTasks = [tasks copy];
        [_lastLoadedTasksLock unlock];
        completionHandler(tasks.count > 0);
      }];
}

+ (NSArray<TTVideoEngineDownloadTask *> *)getLastLoadedTasks {
  [_lastLoadedTasksLock lock];
  NSArray *tasks = s_lastLoadedTasks ? [s_lastLoadedTasks copy] : @[];
  [_lastLoadedTasksLock unlock];

  // 直接返回原始任务对象，不使用包装类
  // 通过禁止 TTVideoEngineDownloadTask 及其子类的 JSON 序列化来避免循环引用
  return tasks;
}

+ (void)resumeAllDownloadTasks {
  [[TTVideoEngineDownloader shareLoader]
      getAllTasksWithCompletionHandler:^(
          NSArray<__kindof TTVideoEngineDownloadTask *> *_Nonnull tasks) {
        if (tasks.count > 0) {
          [[TTVideoEngineDownloader shareLoader] resumeAllTasks];
        }
      }];
}

+ (void)suspendAllDownloadTasks {
  [[TTVideoEngineDownloader shareLoader]
      getAllTasksWithCompletionHandler:^(
          NSArray<__kindof TTVideoEngineDownloadTask *> *_Nonnull tasks) {
        if (tasks.count > 0) {
          [[TTVideoEngineDownloader shareLoader] suspendAllTasks];
        }
      }];
}

+ (void)removeAllDownloadTasks {
  [[TTVideoEngineDownloader shareLoader]
      getAllTasksWithCompletionHandler:^(
          NSArray<__kindof TTVideoEngineDownloadTask *> *_Nonnull tasks) {
        if (tasks.count > 0) {
          [[TTVideoEngineDownloader shareLoader] removeAllTasks];
        }
      }];
}

+ (void)setDownloaderDelegateOnMain:(id)delegate
                         completion:(void (^)(void))completion {
  dispatch_async(dispatch_get_main_queue(), ^{
    [TTVideoEngineDownloader shareLoader].delegate = delegate;
    if (completion) {
      completion();
    }
  });
}

+ (nullable NSString *)getVideoIdFromTask:(nullable TTVideoEngineDownloadTask *)task {
  if (!task) {
    return nil;
  }

  @try {
    // 使用 KVC 获取 videoId；列表任务多为 videoId，delegate 回调里可能为 vid，两者都尝试
    id value = [task valueForKey:@"videoId"];
    if (!value || ![value isKindOfClass:[NSString class]]) {
      value = [task valueForKey:@"vid"];
    }
    if (value && [value isKindOfClass:[NSString class]]) {
      return (NSString *)value;
    }
    return nil;
  } @catch (NSException *exception) {
    return nil;
  }
}

+ (nullable NSString *)getKeyFromTask:(nullable TTVideoEngineDownloadTask *)task {
  if (!task) {
    return nil;
  }

  // 只有 TTVideoEngineDownloadURLTask 才有 key 属性
  Class urlTaskClass = NSClassFromString(@"TTVideoEngineDownloadURLTask");
  if (!urlTaskClass || ![task isKindOfClass:urlTaskClass]) {
    return nil;
  }

  @try {
    // 使用 KVC 获取 key，避免直接属性访问可能导致的 bridge 问题
    id key = [task valueForKey:@"key"];
    if (key && [key isKindOfClass:[NSString class]]) {
      return (NSString *)key;
    }
    return nil;
  } @catch (NSException *exception) {
    return nil;
  }
}

+ (nullable NSArray *)getUrlsFromTask:(nullable TTVideoEngineDownloadTask *)task {
  if (!task) {
    return nil;
  }

  // 只有 TTVideoEngineDownloadURLTask 才有 urls 属性
  Class urlTaskClass = NSClassFromString(@"TTVideoEngineDownloadURLTask");
  if (!urlTaskClass || ![task isKindOfClass:urlTaskClass]) {
    return nil;
  }

  @try {
    // 使用 KVC 获取 urls，避免直接属性访问可能导致的 bridge 问题
    id urls = [task valueForKey:@"urls"];
    if (urls && [urls isKindOfClass:[NSArray class]]) {
      return (NSArray *)urls;
    }
    return nil;
  } @catch (NSException *exception) {
    return nil;
  }
}

+ (nullable NSNumber *)getResolutionFromTask:(nullable TTVideoEngineDownloadTask *)task {
  if (!task) {
    return nil;
  }

  // 只有 TTVideoEngineDownloadVidTask 才有 resolution 属性
  Class vidTaskClass = NSClassFromString(@"TTVideoEngineDownloadVidTask");
  if (!vidTaskClass || ![task isKindOfClass:vidTaskClass]) {
    return nil;
  }

  @try {
    // 使用 KVC 获取 resolution，避免直接属性访问可能导致的 bridge 问题
    id resolution = [task valueForKey:@"resolution"];
    if (resolution && [resolution isKindOfClass:[NSNumber class]]) {
      return (NSNumber *)resolution;
    }
    return nil;
  } @catch (NSException *exception) {
    return nil;
  }
}

+ (nullable NSNumber *)getCodecTypeFromTask:(nullable TTVideoEngineDownloadTask *)task {
  if (!task) {
    return nil;
  }

  // 只有 TTVideoEngineDownloadVidTask 才有 codecType 属性
  Class vidTaskClass = NSClassFromString(@"TTVideoEngineDownloadVidTask");
  if (!vidTaskClass || ![task isKindOfClass:vidTaskClass]) {
    return nil;
  }

  @try {
    // 使用 KVC 获取 codecType，避免直接属性访问可能导致的 bridge 问题
    id codecType = [task valueForKey:@"codecType"];
    if (codecType && [codecType isKindOfClass:[NSNumber class]]) {
      return (NSNumber *)codecType;
    }
    return nil;
  } @catch (NSException *exception) {
    return nil;
  }
}

@end
