//
//  cachesFileManager.m
//  隐私保护
//
//  Created by xd h on 2023/11/21.
//

#import "cachesFileManager.h"

@implementation cachesFileManager


#pragma mark - 获取文件夹（没有的话创建）
+ (NSString *)getCreateFilePath:(NSString *)path {
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}


#pragma mark - 获取文件夹
+ (BOOL)checkFileIsSaveState:(NSString *)fileName withType:(uploadFileType)type
{
    NSString * path = [cachesFileManager getFilePathWithName:fileName type:type];
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

//获取资源名字并且保存资源
+ (NSString *)getFileNameWithContent:(id)content fileName:(NSString*)fileName type:(uploadFileType)type
{
    // 解决服务器文件名有 /
    NSArray *strArr = [fileName componentsSeparatedByString:@"/"];
    
    if (strArr.count >= 2) {
        fileName = strArr.lastObject;
    }
    
    if (!content) {
        return @"";
    }
    
    NSString *filePath;
    NSData *data;
    
    switch (type) {
        case uploadFileTypeImage://image
        {
            filePath = [NSString stringWithFormat:@"%@/%@",kSHPath_image,fileName];
            
            if ([content isKindOfClass:[NSData class]]) {
                data = content;
            }
        }
            break;
        
        case uploadFileTypeVideo://video
        {
            if ([content isKindOfClass:[NSData class]]) {
                data = content;
            }
//            else if ([content isKindOfClass:[NSString class]])
//            {
//                data = [NSData dataWithContentsOfFile:content];
//            }
            filePath = [NSString stringWithFormat:@"%@/%@",kSHPath_video,fileName];
        }
            break;
        
        case DownLoadThumbnail://image
        {
            filePath = [NSString stringWithFormat:@"%@/%@",kSHPath_DownLoadThumbnail,fileName];
            
            if ([content isKindOfClass:[NSData class]]) {
                data = content;
            }
        }
            break;
            
        case DownLoadFileType://
        {
            filePath = [NSString stringWithFormat:@"%@/%@",kSHPath_DownLoadFlie,fileName];
            
            if ([content isKindOfClass:[NSData class]]) {
                data = content;
            }
        }
            break;
            
        default:
            break;
    }
    
    
   
    //创建文件路径
    [cachesFileManager getCreateFilePath:[filePath stringByDeletingLastPathComponent]];
    
    if (data) {
        BOOL ret =  [data writeToFile:filePath atomically:YES];
        if (!ret) {
           HLog(@"\n\n上传文件名写入失败\n\n");
        }
    }
    
    return filePath.length?filePath.lastPathComponent:@"";
}


//获取资源路径
+ (NSString *)getFilePathWithName:(NSString *)name type:(uploadFileType)type
{
    
    // 解决服务器文件名有 /
    NSArray *strArr = [name componentsSeparatedByString:@"/"];
    
    if (strArr.count >= 2) {
        name = strArr.lastObject;
    }
    
    switch (type) {
        case uploadFileTypeImage://image
        {
            name = [NSString stringWithFormat:@"%@/%@",kSHPath_image,name];
        }
            break;
    
        case uploadFileTypeVideo://video
        {
            name = [NSString stringWithFormat:@"%@/%@",kSHPath_video,name];
        }
            break;
        case DownLoadThumbnail://image
        {
            name = [NSString stringWithFormat:@"%@/%@",kSHPath_DownLoadThumbnail,name];
        }
            break;
        case DownLoadFileType://
        {
            name = [NSString stringWithFormat:@"%@/%@",kSHPath_DownLoadFlie,name];
        }
            break;
        default:
            break;
    }
    
    return name;
}

+ (BOOL)removeItemAtPath:(NSString *)fileName type:(uploadFileType)type error:(NSError *__autoreleasing *)error {
    NSString *curPath = [cachesFileManager getFilePathWithName:fileName type:type];
            
    BOOL success = [[NSFileManager defaultManager] removeItemAtPath:curPath error:error];
    if (success) {
        // 文件删除成功
    } else {
        // 文件删除失败
        NSLog(@"删除文件失败：%@-----%@",fileName,error);
    }
    
    return success;
}

+ (BOOL)copyVideoItemAtPath:(NSString *)Path fileName:(NSString *)fileName error:(NSError *__autoreleasing *)error {
    NSString *curPath = [cachesFileManager getFilePathWithName:fileName type:uploadFileTypeVideo];
            
    BOOL success = [[NSFileManager defaultManager] copyItemAtPath:Path toPath:curPath error:error];
    if (success) {
        // 文件删除成功
    } else {
        // 文件删除失败
        NSLog(@"删除文件失败：%@-----%@",fileName,error);
    }
    
    return success;
}

//写日志
+ (void)writeLogsWithMsg:(NSString *)msg
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:kSHPath_logs]) {
        
        [[NSFileManager defaultManager] createDirectoryAtPath:kSHPath_logs withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *logFilePath = [kSHPath_logs stringByAppendingPathComponent:@"app.log"];
      
    // 创建或打开文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:logFilePath]) {
        // 如果文件不存在，则创建它
        NSError *error;
        if (![[NSFileManager defaultManager] createFileAtPath:logFilePath contents:nil attributes:nil]) {
            NSLog(@"Unable to create file: %@", logFilePath);
        }
    }
      
    // 准备写入文件
    long long endOfFile = 0;
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath]; // 创建文件句柄
    if (fileHandle) {
        endOfFile = [fileHandle seekToEndOfFile];
        if (endOfFile >=  0) {
            NSString *allMsg = [[NSString alloc] initWithFormat:@"%@ %@\n",[iTools getNowTimeString2],msg];
            NSData *fileData =[allMsg dataUsingEncoding:NSUTF8StringEncoding];
            [fileHandle writeData:fileData];
        }
        
        endOfFile = [fileHandle seekToEndOfFile];
        // 关闭文件句柄
        [fileHandle closeFile];
    }
    
}
@end
