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

#import "RCTRnUpdateDownload.h"
#import "RCTRnUpdateResultParams.h"

@interface RCTRnUpdateDownload()<NSURLSessionDelegate>

// 进度条回调函数
@property (copy) void (^progressHandler)(long currentSize, long totalSize, double progress);

// 下载状态回调函数
@property (copy) void (^completionHandler)(NSString *statusCode, NSString *msg);
// 保存位置
@property (copy) NSString *savePath;
// 下载路径
@property (copy) NSString *downloadUrl;
@end

@implementation RCTRnUpdateDownload

// 下载文件
+ (void)downloadFile:(NSString *)url savePath:(NSString *)savePath
   progressHandler:(void (^)(long currentSize, long totalSize, double progress))progressHandler
   completionHandler:(void (^)(NSString *statusCode, NSString *msg))completionHandler
{
  RCTRnUpdateDownload *ins = [RCTRnUpdateDownload new];
  ins.progressHandler = progressHandler;
  ins.completionHandler = completionHandler;
  ins.savePath = savePath;
  
  [ins download:url];
}

- (void)download:(NSString *)path
{
  
    NSString *encodedPath =
      [path stringByAddingPercentEncodingWithAllowedCharacters:
       [NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *url = [NSURL URLWithString:encodedPath];
  
    self.downloadUrl = path;
  
//    NSURL *url = [NSURL URLWithString:path];
  
    NSLog(@"[RCTRnUpdate LOG] RCTRnUpdateDownload -- download url: %@", url);
  
    
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
                                                          delegate:self
                                                     delegateQueue:nil];
    
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
    [task resume];
}

#pragma mark - session delegate

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
#ifdef DEBUG
    NSLog(@"[RCTRnUpdate LOG] RCTRnUpdateDownload --  progress, %lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
#endif
    
    if (self.progressHandler) {
      // 计算下载进度
        double progress = ((double)totalBytesWritten / (double)totalBytesExpectedToWrite) * 100;
        
        self.progressHandler(totalBytesWritten ,totalBytesExpectedToWrite, progress);
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSData *data = [NSData dataWithContentsOfURL:location];
    NSError *error;
    [data writeToFile:self.savePath options:NSDataWritingAtomic error:&error];
    if (error) {
        if (self.completionHandler) {
          self.completionHandler(
             [NSString stringWithFormat:@"%@", @(RCTRnUpdateResultParams.errorRuntime.code)],
                                 [NSString stringWithFormat:@"[RCTRnUpdate LOG] RCTRnUpdateDownload -- 下载任务失败 [didFinishDownloadingToURL]，下载路径：%@, 错误信息：%@", self.downloadUrl, error.localizedDescription]
           );
            self.completionHandler = nil;
        }
    }
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    if (self.completionHandler) {
      if(error) {
        self.completionHandler(
           [NSString stringWithFormat:@"%@", @(RCTRnUpdateResultParams.errorRuntime.code)],
                               [NSString stringWithFormat:@"[RCTRnUpdate LOG] RCTRnUpdateDownload -- 下载任务失败， [didCompleteWithError]， 下载路径：%@, 错误信息：%@", self.downloadUrl, error.localizedDescription]
         );
        return;
      }
      // 检查 HTTP 状态码
      NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
      if (response.statusCode != 200) {
        
        NSLog(@"[RCTRnUpdate LOG] RCTRnUpdateDownload -- 下载失败， [didCompleteWithError]， statusCode：%ld", response.statusCode);
        
        NSInteger code = response.statusCode;
        if(code == 404) {
          code = RCTRnUpdateResultParams.errorNotExist.code;
        }
        
        self.completionHandler([NSString stringWithFormat:@"%@", @(code)], [NSString stringWithFormat:@"下载失败，网络状态错误：%ld", (long)response.statusCode]);
        return;
      }
      
      self.completionHandler(
         [NSString stringWithFormat:@"%@", @(RCTRnUpdateResultParams.success.code)],
         [NSString stringWithFormat:@"%@", RCTRnUpdateResultParams.success.msg]
      );
    }
}

@end
