//
//  HWMFileManager.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2021/7/26.
//  Copyright © 2021 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMSDKDemoFileManager.h"

@implementation HWMSDKDemoFileManager

+ (BOOL)isExist:(NSString *)path {
    BOOL result = [[NSFileManager defaultManager] fileExistsAtPath:path];
    return result;
}

+ (NSDictionary *)mkDir:(NSString *)dirPath recursive:(BOOL)recursive {
    // iOS 系统方法会循环创建路径，需要提前判断不循环创建路径的错误
    if (!recursive) {
        NSString *parentDir = [dirPath stringByDeletingLastPathComponent];
        if (![[NSFileManager defaultManager] fileExistsAtPath:parentDir]) {
            return @{ @"result": @(NO), @"errMsg": [NSString stringWithFormat:@"fail no such file or directory %@", parentDir] };
        }
    }
    NSError *error;
    if ([[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error]) {
        return @{ @"result": @(YES) };
    } else {
        return @{ @"result": @(NO), @"errMsg": error.localizedFailureReason };
    }
}

static NSString *g_appSupportDir = nil;
+ (NSString *)applicationSupportDir {
    if (g_appSupportDir != nil) {
        return g_appSupportDir;
    }

    g_appSupportDir =   [self dirPath:NSApplicationSupportDirectory];
    return g_appSupportDir;
}

+ (NSString *)dirPath:(NSSearchPathDirectory)directory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    NSString *applicationDir = [paths objectAtIndex:0];
    NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleNameKey];
    applicationDir = [applicationDir stringByAppendingPathComponent:bundleName];

    return applicationDir;
}

+ (NSString *)pcmPath {
    NSString *pcmDirectory = [[self applicationSupportDir] stringByAppendingFormat:@"/pcm"];
   
    if ([self isExist:pcmDirectory]) {
        return pcmDirectory;
    }
    [self mkDir:pcmDirectory recursive:YES];
    return pcmDirectory;
}

@end
