//
//  RCTRnUpdateFileManager.m
//  LocalApp
//
//  Created by edy on 2026/1/5.
//

#import "RCTRnUpdateFileManager.h"
#import "react/RCTConvert.h"
//#import "ZipArchive.h"
#import "SSZipArchive.h"


@implementation RCTRnUpdateFileManager {
  dispatch_queue_t _opQueue;
}

- (instancetype) init
{
  self = [super init];
  if(self) {
    _opQueue = dispatch_queue_create("com.xiaoyudesign.rnupdate", DISPATCH_QUEUE_SERIAL);
  }
  return self;
}

- (BOOL)createDir:(NSString *)dir
{
    __block BOOL success = false;
    
    dispatch_sync(_opQueue, ^{
        BOOL isDir;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:dir isDirectory:&isDir]) {
            if (isDir) {
                success = true;
                return;
            }
        }
        
        NSError *error;
        [fileManager createDirectoryAtPath:dir
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error];
        if (!error) {
            success = true;
            return;
        } else {
          RCTLogInfo(@"[RCTRnUpdate LOG] RCTRnUpdateFileManager -- createDir dir: %@, error: %@ ", dir, error.localizedFailureReason);
        }
    });
    
    return success;
}

// 检查文件是否存在
- (BOOL)checkZipFileExists:(NSString *)zipPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 检查文件是否存在
    if (![fileManager fileExistsAtPath:zipPath]) {
        NSLog(@"❌ ZIP文件不存在: %@", zipPath);
        return NO;
    }
    
    // 检查是否是文件而不是目录
    BOOL isDirectory;
    if ([fileManager fileExistsAtPath:zipPath isDirectory:&isDirectory] && isDirectory) {
        NSLog(@"❌ 路径指向的是目录而不是文件: %@", zipPath);
        return NO;
    }
    
    NSLog(@"✅ ZIP文件存在: %@", zipPath);
    return YES;
}

+ (BOOL)checkFileExists:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 检查文件是否存在
    if (![fileManager fileExistsAtPath:filePath]) {
        NSLog(@"❌ 文件不存在: %@", filePath);
        return NO;
    }
    
    // 检查是否是文件而不是目录
    BOOL isDirectory;
    if ([fileManager fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
        NSLog(@"❌ 路径指向的是目录而不是文件: %@", filePath);
        return NO;
    }
    
    NSLog(@"✅ 文件存在: %@", filePath);
    return YES;
}

// 解压文件
- (void)unzipFile:(NSString *)zipPath toDestination:(NSString *)destination
  progressHandler:(void (^)(NSString *entry, long entryNumber, long total, double progress))progressHandler
completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError *error))completionHandler
{
  dispatch_async(_opQueue, ^{
//    if ([[NSFileManager defaultManager] fileExistsAtPath:destination]) {
//         [[NSFileManager defaultManager] removeItemAtPath:destination error:nil];
//     }
    
    [SSZipArchive unzipFileAtPath:zipPath toDestination:destination progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
      // 计算下载进度
        double progress = ((double)entryNumber / (double)total) * 100;
      
        progressHandler(entry, entryNumber, total, progress);
    } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
        // 解压完，移除zip文件
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        if (completionHandler) {
            completionHandler(path, succeeded, error);
        }
    }];
    
  });
}


@end
