//
//  HWSetViewController.m
//  双子星云手机
//
//  Created by 余衡武 on 2022/3/24.
//

#import "HWSetViewController.h"
#import "HWAgreementViewController.h"
#import "HWAboutViewController.h"
#import <WebKit/WebKit.h>

@interface HWSetViewController ()

@property (weak, nonatomic) IBOutlet UIView  *bgViewOne;
@property (weak, nonatomic) IBOutlet UIView  *bgViewTwo;
@property (weak, nonatomic) IBOutlet UIView  *bgViewThree;
@property (weak, nonatomic) IBOutlet UILabel *storeLabel;
@property (weak, nonatomic) IBOutlet UIView  *header;

@end

@implementation HWSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.header mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(NAVIHEIGHT);
    }];

    [self.bgViewOne addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgViewOneDidClick)]];
    [self.bgViewTwo addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgViewTwoDidClick)]];
    [self.bgViewThree addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgViewThreeDidClick)]];
    
    self.bgViewOne.layer.cornerRadius = 10;
    self.bgViewOne.layer.masksToBounds = YES;
    self.bgViewTwo.layer.cornerRadius = 10;
    self.bgViewTwo.layer.masksToBounds = YES;
    self.bgViewThree.layer.cornerRadius = 10;
    self.bgViewThree.layer.masksToBounds = YES;
    [self.bgViewThree setHidden:YES];
    self.storeLabel.text = [self getCacheSize];
}

- (IBAction)backBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)bgViewOneDidClick {
    HLog(@"清除缓存");
    [self toShowTips];
}

- (void)bgViewTwoDidClick {
    HLog(@"关于我们");
    HWAboutViewController *vc = [[HWAboutViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)bgViewThreeDidClick {
    HLog(@"隐私政策");
    HWAgreementViewController *vc = [[HWAgreementViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toShowTips {

    NSString *tipsStr = NSLocalizedString(@"app_set_clear_cache",nil);

    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clearWebViewCache];
    }];
    [sureAction setValue:[UIColor hwColor:@"#3B7FFF"] forKey:@"titleTextColor"];//iOS8.3
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_cancel",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [cancelAction setValue:[UIColor colorWithHexString:@"#FFFFFF" alpha:0.5] forKey:@"titleTextColor"];//iOS8.3
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
    alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
    
    [alertVC addAction:sureAction];
    [alertVC addAction:cancelAction];

    [self presentViewController:alertVC animated:YES completion:^{
        
    }];
}

- (NSString *)getCacheSize {
    
    /* 取得Library文件夹的位置*/
     NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
     /* 取得bundle id，用作文件拼接用*/
     NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleIdentifier"];
     /*
      * 拼接缓存地址，具体目录为App/Library/Caches/你的APPBundleID/fsCachedData
      */
     NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
    
    NSError *error;
    /* 取得目录下所有的文件，取得文件数组*/
    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSArray *fileList = [[NSArray alloc] init];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:webKitFolderInCachesfs error:&error];
    NSInteger fileSize = 0;
    /* 遍历文件组成的数组*/
    for(NSString *fileName in fileList){
        /* 定位每个文件的位置*/
        NSString * path = [[NSBundle bundleWithPath:webKitFolderInCachesfs] pathForResource:fileName ofType:@""];
        /* 将文件转换为NSData类型的数据*/
        NSData *fileData = [NSData dataWithContentsOfFile:path];
        /* 如果FileData的长度大于2，说明FileData不为空*/
        if(fileData.length >2){
            /* 创建两个用于显示文件类型的变量*/
            int char1 =0;
            int char2 =0;

            [fileData getBytes:&char1 range:NSMakeRange(0,1)];
            [fileData getBytes:&char2 range:NSMakeRange(1,1)];
            /* 拼接两个变量*/
            NSString *numStr = [NSString stringWithFormat:@"%i%i",char1,char2];
            /* 如果该文件前四个字符是6033，说明是Html文件，删除掉本地的缓存*/
            if([numStr isEqualToString:@"6033"]){
//                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",webKitFolderInCachesfs,fileName]error:&error];
                fileSize += fileData.length;
                continue;
            }
        }
    }
    
    return [iTools getFileSizeStringFormedValue:fileSize];
}



- (void)clearWebViewCache {
    NSArray * types = @[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
    NSSet *websiteDataTypes = [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        HLog(@"缓存清理完成");
        self.storeLabel.text = @"0MB";
        [[iToast makeText:@"缓存清理完成"] show];
    }];
    
//    /* 取得Library文件夹的位置*/
//     NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
//     /* 取得bundle id，用作文件拼接用*/
//     NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleIdentifier"];
//     /*
//      * 拼接缓存地址，具体目录为App/Library/Caches/你的APPBundleID/fsCachedData
//      */
//     NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
//
//    NSError *error;
//    /* 取得目录下所有的文件，取得文件数组*/
//    NSFileManager *fileManager = [NSFileManager defaultManager];
////    NSArray *fileList = [[NSArray alloc] init];
//    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
//    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:webKitFolderInCachesfs error:&error];
//    /* 遍历文件组成的数组*/
//    for(NSString * fileName in fileList){
//        /* 定位每个文件的位置*/
//        NSString * path = [[NSBundle bundleWithPath:webKitFolderInCachesfs] pathForResource:fileName ofType:@""];
//        /* 将文件转换为NSData类型的数据*/
//        NSData * fileData = [NSData dataWithContentsOfFile:path];
//        /* 如果FileData的长度大于2，说明FileData不为空*/
//        if(fileData.length >2){
//            /* 创建两个用于显示文件类型的变量*/
//            int char1 =0;
//            int char2 =0;
//
//            [fileData getBytes:&char1 range:NSMakeRange(0,1)];
//            [fileData getBytes:&char2 range:NSMakeRange(1,1)];
//            /* 拼接两个变量*/
//            NSString *numStr = [NSString stringWithFormat:@"%i%i",char1,char2];
//            /* 如果该文件前四个字符是6033，说明是Html文件，删除掉本地的缓存*/
//            if([numStr isEqualToString:@"6033"]){
//                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",webKitFolderInCachesfs,fileName]error:&error];
//                continue;
//            }
//        }
//    }
//
//    self.storeLabel.text = [self getCacheSize];
//    [[iToast makeText:@"缓存清理完成"] show];
}

@end
