//
//  testTableViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 14-8-5.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "CacheViewController.h"
#import "RAUtils.h"
#import "AppDelegate.h"

#define AL_CACHE 1234
#define AL_CLEAN 1235
@interface CacheViewController ()

@end

@implementation CacheViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)onCloseClick:(id)sender {
    [self dismissViewControllerAnimated:true completion:nil];
    
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    

   AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    
   
//    
//
    if( appDelegate.bEnable_Cache)
    {
        self.catchSwitch.on=true;
         self.sizeLabel.text = @"Calculating";
        // 创建
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(calculate) object:nil];
        // 启动
        [thread start];
    }
    else
    {
        self.catchSwitch.on=false;
         self.sizeLabel.text = @"";
         [self.mum stopAnimating];
    }
    
    
    UIBarButtonItem* closeBTN = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                   style:UIBarButtonItemStylePlain
                                                  target:self
                                                  action:@selector(onCloseClick:)];
    
    
    self.navigationItem.rightBarButtonItem = closeBTN;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    


    

}
- (void)calculate
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachefolder = [paths objectAtIndex:0];
    NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
    
//    DebugLog(@"%@",cachefolder);
//     DebugLog(@"%@",img_cache);
    float size=[RAUtils fileSizeForDir:img_cache];
   // float size1=[RAUtils fileSizeForDir:img_cache];
    
        self.sizeLabel.text = [NSString stringWithFormat:@" %.2f MB",size];
    
    [self.mum stopAnimating];

}

- (void)clear
{
    
    
    
    UIAlertView * alert = [RAUtils waiting_alert:@"Deleting..." title:nil];
    
//    UIAlertView * alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Deleting", nil) message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    
    
    //   alert.tag = AL_CACHE;
    
    
    
//    [alert show];
    


    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachefolder = [paths objectAtIndex:0];
        NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
    
    
    [RAUtils deletefiles:img_cache];
    [RAUtils deletefiles: cachefolder];
    //    DebugLog(@"%@",cachefolder);
    //     DebugLog(@"%@",img_cache);
//    float size=[RAUtils fileSizeForDir:cachefolder];
//    // float size1=[RAUtils fileSizeForDir:img_cache];
//    
//    self.sizeLabel.text = [NSString stringWithFormat:@"Cache size: %.2f MB",size];
//    
//    [self.mum stopAnimating];
    
    
     [alert dismissWithClickedButtonIndex:0 animated:FALSE];
    
    [self.mum startAnimating];
    float size=[RAUtils fileSizeForDir:cachefolder];
    // float size1=[RAUtils fileSizeForDir:img_cache];
    
    self.sizeLabel.text = [NSString stringWithFormat:@"Cache size: %.2f MB",size];
    
    [self.mum stopAnimating];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)cacheSwitchChanged:(UISwitch *)sender {
    
    if(!sender.on)
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Disable Cache Confirm", nil) message:NSLocalizedString(@"Disable cache will save some diskspace but cost more network traffic and also slower. Are you sure to Disable cache?", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"NO", nil) otherButtonTitles:NSLocalizedString(@"YES", nil), nil];
        
        
        alert.tag = AL_CACHE;
        

        
        [alert show];
    }
    else
    {
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        
        
                    [defaults setValue:@"true" forKey:@"enable_cache"];

        
        [defaults synchronize];
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        appDelegate.bEnable_Cache = true;
          }
}
#pragma mark - UIAlertViewDelegate
// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==AL_CACHE)
    {
        if(buttonIndex!=alertView.cancelButtonIndex)
        {
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        
        
        [defaults setValue:@"false" forKey:@"enable_cache"];
        
        [defaults synchronize];
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        appDelegate.bEnable_Cache = false;
        
        
        // 创建
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(clear) object:nil];
        // 启动
        [thread start];
        return;
        }
        else
            self.catchSwitch.on=YES;
        
        
    }
    
        if(buttonIndex!=alertView.cancelButtonIndex&&alertView.tag==AL_CLEAN)
        {
            // 创建
            NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(clear) object:nil];
            // 启动
            [thread start];
            return;
        }
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==2)
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Clear Cache Confirm", nil) message:NSLocalizedString(@"Clear cache will take some time, click YES to confirm clear.", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"NO", nil) otherButtonTitles:NSLocalizedString(@"YES", nil), nil];
        
        
        alert.tag = AL_CLEAN;
        
        
        
        [alert show];
    }
//    NSString* title = [self.settingMenuItems[indexPath.row] valueForKey:@"title"];
//    if([title isEqualToString:@"Cache"])
//    {
//        CacheViewController* tvc = [self.storyboard instantiateViewControllerWithIdentifier:@"CacheViewController" ];
//        
//        
//        [self.navigationController pushViewController:tvc animated:true];
//        //        PopupNavigationController * navi=[ self.storyboard instantiateViewControllerWithIdentifier:@"PopupNavi"];
//        //
//        //
//        //
//        //        navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态，自己看看是哪种
//        //        [self presentViewController:navi animated:YES completion:^{
//        //
//        //            //DebugLog(@"login.........");
//        //            //  <#code#>
//        //        }];
//        //
//        //
//        //
//        
//    }
//    else if([title isEqualToString:@"Price"])
//    {
//        //        [self hideMenu];
//        //        if([self.current_VC isKindOfClass:[WatchListViewController class]])
//        //            return;
//        //        [self flipFromViewController:self.current_VC toViewController:self.watchListViewController withDirection:UIViewAnimationOptionTransitionCrossDissolve];
//    }
}

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return 0;
//}

//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//#warning Incomplete method implementation.
//    // Return the number of rows in the section.
//    return 0;
//}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
