//
//  IMSiLopOALocalizeManage.m
//  IMSOpenAccountCustom
//
//  Created by chuntao.wang1 on 2019/4/15.
//

#import "IMSiLopOALocalizeManage.h"
#import "IMSiLopOALanguageManage.h"
#import <UIKit/UIKit.h>

@interface IMSiLopOALocalizeManage ()

@property (nonatomic, strong) NSMutableDictionary *bundleCache;

@end

@implementation IMSiLopOALocalizeManage

#pragma mark - Init

+ (instancetype)sharedInstance {
    static IMSiLopOALocalizeManage *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });

    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _bundleCache = [[NSMutableDictionary alloc] init];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(didReceiveMemoryWarning)
                                                     name:UIApplicationDidReceiveMemoryWarningNotification
                                                   object:nil];
    }
    return self;
}

#pragma mark - Interface

+ (NSString *)localizedString:(NSString *)key inBundle:(NSString *)bundleName {
    NSAssert(key != nil, @"localized key can not be nil");
    NSAssert(bundleName != nil, @"localized bundleName can not be nil");
    
    NSBundle *bundle = [[IMSiLopOALocalizeManage sharedInstance] bundleWithName:bundleName];
    if (bundle) {
        return NSLocalizedStringFromTableInBundle(key, nil, bundle, nil);
    }
    return nil;
}

#pragma mark - Method

- (NSBundle *)bundleWithName:(NSString *)bundleName {
    if (bundleName.length > 0) {
        // 优先从缓存里取bundle
        id bundle = [self.bundleCache objectForKey:bundleName];
        if (bundle) {
            return bundle;
        }
        
        NSBundle *moduleBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:bundleName ofType:@"bundle"]];
        if (moduleBundle) {
            // 中文(如：zh-Hans-US)统一使用zh.lproj，英文(如：en-US)统一使用en.lproj
            NSString *currentLanguage = [[IMSiLopOALanguageManage shareInstance] currentLanguagePrefix];
            if (currentLanguage.length < 2) {
                currentLanguage = @"zh";
            }
            NSString *lprojName = [currentLanguage substringWithRange:NSMakeRange(0, 2)] ?: @"zh";
            bundle = [NSBundle bundleWithPath:[moduleBundle pathForResource:lprojName ofType:@"lproj"]];
            if (bundle) {
                [self.bundleCache setValue:bundle forKey:bundleName];
            }
            return bundle;
        }
    }
    return nil;
}

+ (void)cleanCache {
    [[IMSiLopOALocalizeManage sharedInstance].bundleCache removeAllObjects];
}

- (void)didReceiveMemoryWarning {
    [self.bundleCache removeAllObjects];
}

@end
