//
//  UIApplication+Customized.m
//  DingDCommunity
//
//  Created by JianjiYuan on 14-5-1.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "UIApplication+Customized.h"
#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "DBDaoMgr.h"

@implementation UIApplication (Customized)

+ (void)saveObject:(id)object type:(ObjectType)type key:(NSString *)key;
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    id objectData = nil;
    switch (type) {
        case String: objectData = object?:@""; break;
        case Number: objectData = object?:@0; break;
        case Array: objectData = object?:@[]; break;
        case Dictionary: objectData = object?:@{}; break;
        default:
            break;
    }
    [userDefault setObject:objectData forKey:key];
    [userDefault synchronize];
}

+ (id)getObjectType:(ObjectType)type key:(NSString *)key
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    id objectData = nil;
    switch (type) {
        case String: objectData = [userDefault stringForKey:key]?:@""; break;
        case Number: objectData = [userDefault objectForKey:key]?:@0; break;
        case Array: objectData = [userDefault arrayForKey:key]?:@[]; break;
        case Dictionary: objectData = [userDefault dictionaryForKey:key]?:@{}; break;
        default:
            break;
    }
    return objectData;
}

+ (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate tag:(NSInteger)tag cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:delegate
                                          cancelButtonTitle:cancelButtonTitle
                                          otherButtonTitles:otherButtonTitles, nil];
    if(tag > 0)
        alert.tag = tag;
    
    if ([[NSThread currentThread] isMainThread]) {
        [alert show];
        
    }else {
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    }
    
}

+ (void)showLoadingView:(NSString *)message
{
    UIView *rootView = nil;
    if ([UIApplication sharedApplication].windows.count > 1) {
        int windowsCount = (int)[UIApplication sharedApplication].windows.count;
        for (int i = windowsCount-1; i >= 0 ; i--) {
            UIWindow *window = [UIApplication sharedApplication].windows[i];
            if (window.windowLevel < UIWindowLevelStatusBar &&
                CGRectEqualToRect(window.frame, [UIScreen mainScreen].bounds)) {
                rootView = window;
                break;
            }
        }
        if (!rootView) {
            rootView = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
        }
    }else {
        rootView = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
    }
    
    for (UIView *subView in rootView.subviews) {
        if ([subView isKindOfClass:[MBProgressHUD class]]) {
            [subView removeFromSuperview];
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
//        [MBProgressHUD showHUDAddedTo:rootView message:message animated:YES];
    });
    
    
}

+ (void)hideLoadingView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        for (UIWindow *window in [UIApplication sharedApplication].windows) {
            for (UIView *subView in window.subviews) {
                if ([subView isKindOfClass:[MBProgressHUD class]]) {
                    [subView removeFromSuperview];
                }
            }
            
        }
        
    });
    
}

+ (void)showToastViewMessage:(NSString *)message
{
    CGRect rect = [[UIScreen mainScreen] bounds];
    
    UIView *rootView = nil;
    if ([UIApplication sharedApplication].windows.count > 1) {
        int windowsCount = (int)[UIApplication sharedApplication].windows.count;
        for (int i = windowsCount-1; i >= 0 ; i--) {
            UIWindow *window = [UIApplication sharedApplication].windows[i];
            if (window.windowLevel < UIWindowLevelStatusBar &&
                CGRectEqualToRect(window.frame, [UIScreen mainScreen].bounds)) {
                rootView = window;
                break;
            }
        }
        if (!rootView) {
            rootView = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
        }
        
    }else {
        rootView = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIView *toast = [rootView viewWithTag:99999];
        if (toast) {
            toast.alpha = 0;
            [toast removeFromSuperview];
        }
        
        [rootView makeToast:message
                   duration:3.5
                   position:[NSValue valueWithCGPoint:CGPointMake(CGRectGetWidth(rect)/2, CGRectGetHeight(rect)-100)]
                      title:nil];
    });
    
}

+ (void)showNoResultView:(UIView *)superView desc:(NSString *)desc
{
    [self hideNoResultView:superView];
    
    UIImageView *imageVIcon = [[UIImageView alloc] initWithFrame:CGRectZero];
    [superView addSubview:imageVIcon];
    [imageVIcon setFrame:CGRectMake((CGRectGetWidth(superView.frame)-61)/2,
                                    (CGRectGetHeight(superView.frame)-100)/2, 61, 61)];
    imageVIcon.autoresizingMask = UIViewAutoresizingNone;
    imageVIcon.image = [UIImage imageNamed:@"image_failure.png"];
    
    imageVIcon.tag = 10000;
    
    UILabel *lblDesc = [[UILabel alloc] initWithFrame:CGRectZero];
    lblDesc.textColor = [UIColor lightGrayColor];
    lblDesc.font = [UIFont systemFontOfSize:16];
    lblDesc.textAlignment = NSTextAlignmentCenter;
    lblDesc.backgroundColor = [UIColor clearColor];
    lblDesc.numberOfLines = 0;
    lblDesc.text = [desc validDataOfClass:[NSString class]];
    [superView addSubview:lblDesc];
    
    lblDesc.tag = 10001;
    [lblDesc setFrame:CGRectMake(0, CGRectGetMaxY(imageVIcon.frame)+4, CGRectGetWidth(superView.frame), 21)];
}

+ (void)hideNoResultView:(UIView *)superView
{
    UIView *imageVIcon = [superView viewWithTag:10000];
    UIView *lblDesc = [superView viewWithTag:10001];
    
    [imageVIcon removeFromSuperview];
    [lblDesc removeFromSuperview];
}

+ (UIImageView *)showNoResultImageView:(UIView *)superView imageName:(NSString *)imageName
{
    [self hideNoResultImageView:superView];
    
    UIImageView *imageVIcon = [[UIImageView alloc] initWithFrame:CGRectZero];
    [superView addSubview:imageVIcon];
    [imageVIcon setFrame:CGRectMake((CGRectGetWidth(superView.frame)-150)/2,
                                    (CGRectGetHeight(superView.frame)-180)/2, 150, 150)];
    imageVIcon.autoresizingMask = UIViewAutoresizingNone;
    imageVIcon.image = [UIImage imageNamed:imageName];
    
    imageVIcon.tag = 20000;
    
    return imageVIcon;
}

+ (void)hideNoResultImageView:(UIView *)superView
{
    UIView *imageVIcon = [superView viewWithTag:20000];
    [imageVIcon removeFromSuperview];
}


+ (void)downloadFileURL:(NSString *)aUrl fileName:(NSString *)aFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DEFAULT_DB_NAME];
    
    //检查本地文件是否已存在
    NSString *fileName = [NSString stringWithFormat:@"%@/%@", documentsDirectory, aFileName];
    
    //检查附件是否存在
    if ([fileManager fileExistsAtPath:fileName]) {
        //NSData *audioData = [NSData dataWithContentsOfFile:fileName];
        //[self requestFinished:[NSDictionary dictionaryWithObject:audioData forKey:@"res"] tag:aTag];
    }else{
        //创建附件存储目录
        if (![fileManager fileExistsAtPath:documentsDirectory]) {
            [fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        //下载附件
        NSURL *url = [[NSURL alloc] initWithString:aUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.inputStream   = [NSInputStream inputStreamWithURL:url];
        operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];
        
        //        下载进度控制
        
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            //NSLog(@"is download：%f", (float)totalBytesRead/totalBytesExpectedToRead);
            [DBDaoMgr updateInstructionBookInfoSize:[NSString stringWithFormat:@"%lld",totalBytesRead] ByName:aFileName];
        }];
        
        
        //已完成下载
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            //NSData *audioData = [NSData dataWithContentsOfFile:fileName];
            //设置下载数据到res字典对象中并用代理返回下载数据NSData
            // [self requestFinished:[NSDictionary dictionaryWithObject:audioData forKey:@"res"] tag:aTag];
            [DBDaoMgr updateInstructionBookInfoStatus:@"YES" ByName:aFileName];
            NSNotification *notification =[NSNotification notificationWithName:@"downSuccess" object:nil userInfo:nil];
            //通过通知中心发送通知
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [DBDaoMgr deleteInstructionBookInfoByName:aFileName];
            
            NSFileManager* fileManager=[NSFileManager defaultManager];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
            
            //文件名
            NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:aFileName];
            BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
            if (!blHave) {
                NSLog(@"no  have");
                return ;
            }else {
                NSLog(@" have");
                BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
                if (blDele) {
                    NSLog(@"dele success");
                }else {
                    NSLog(@"dele fail");
                }
                
            }
            
            NSNotification *notification =[NSNotification notificationWithName:@"downFail" object:nil userInfo:nil];
            //通过通知中心发送通知
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            //下载失败
            //            /[self requestFailed:aTag];
        }];
        
        [operation start];
        
        NSNotification *notification =[NSNotification notificationWithName:@"startDown" object:nil userInfo:nil];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }
}
+(BOOL)deleteFileByFileName:(NSString*)fileName {
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        NSLog(@"no  have");
        return YES;
    }else {
        NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            return YES;;
        }else {
            return NO;
        }
        
    }
}
@end