//
//  FWAppDelegate.m  com.feasycom.feasybeacon
//  FeasyBeacon
//
//  Created by LIDONG on 14-2-23.
//  Copyright (c) 2014年 LIDONG. All rights reserved.
//

#import "FWAppDelegate.h"
#import "FWRootViewController.h"
#import "FWUpdateViewController.h"
#import "NSString+FscKit.h"
#import "GTMBase64.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <AFNetworking/AFNetworking.h>
#import <Bugly/Bugly.h>
#import "FSCLogExportManager.h"
#import "FBVersionCheck.h"

extern void FWGlobalIntialize(void);

static void GlobalInitialize(UIApplication *application) {
    theApplication = application;
    
    UIScreen *mainScreen = [UIScreen mainScreen];
    
    CGRectPortraitScreen = [mainScreen bounds];
    CGRectPortraitLongVC = CGRectPortraitScreen;
    CGRectPortraitLongVC.size.height -= 64;
    CGRectPortraitShortVC = CGRectPortraitLongVC;
    CGRectPortraitShortVC.size.height -= 44;
    
    CGRectLandscapeScreen.size.width = CGRectPortraitScreen.size.height;
    CGRectLandscapeScreen.size.height = CGRectPortraitScreen.size.width;
    CGRectLandscapeLongVC = CGRectLandscapeScreen;
    CGRectLandscapeLongVC.size.height -= 52;
    CGRectLandscapeShortVC = CGRectLandscapeLongVC;
    CGRectLandscapeShortVC.size.height -= 32;
    
    UIColorClear = [UIColor clearColor];
    UIColorWhite = [UIColor whiteColor];
    UIColorBlack = [UIColor blackColor];
    UIColorGray = [UIColor grayColor];
    UIColorDarkGray = [UIColor darkGrayColor];
    UIColorLightGray = [UIColor lightGrayColor];
    UIColorDarkCyan = UIColorCreateGenericRGB(0.f, 0.35f, 0.5f);
    UIColorPDFBackground = UIColorCreateGenericRGB(0.45f, 0.55f, 0.53f);
    UIColorTexturedBackground = [UIColor darkGrayColor];
    UIColorViewFlipsideBackground = [UIColor darkGrayColor];
    UIColorSelectedBackground = UIColorCreateGenericRGB(0.93f, 0.95f, 1.f);
    
    CGColorClear = [UIColorClear CGColor];
    CGColorWhite = [UIColorWhite CGColor];
    CGColorBlack = [UIColorBlack CGColor];
    CGColorGray = [UIColorGray CGColor];
    CGColorDarkGray = [UIColorDarkGray CGColor];
    CGColorLightGray = [UIColorLightGray CGColor];
    CGColorDarkCyan = [UIColorDarkCyan CGColor];
    CGColorPDFBackground = [UIColorPDFBackground CGColor];
    CGColorTexturedBackground = [UIColorTexturedBackground CGColor];
    CGColorViewFlipsideBackground = [UIColorViewFlipsideBackground CGColor];
    CGColorSelectedBackground = [UIColorSelectedBackground CGColor];
    
    UIFontNormal10 = [UIFont systemFontOfSize:10];
    UIFontNormal12 = [UIFont systemFontOfSize:12];
    UIFontNormal14 = [UIFont systemFontOfSize:14];
    UIFontNormal16 = [UIFont systemFontOfSize:16];
    UIFontBold10 = [UIFont boldSystemFontOfSize:10];
    UIFontBold12 = [UIFont boldSystemFontOfSize:12];
    UIFontBold14 = [UIFont boldSystemFontOfSize:14];
    UIFontBold16 = [UIFont boldSystemFontOfSize:16];
    UIFontBold18 = [UIFont boldSystemFontOfSize:18];
    
    NSString *homeDirectory = NSHomeDirectory();
    
    FSDocumentsDirectory = [[homeDirectory stringByAppendingPathComponent:@"Documents"] copy];
    FSDownloadsDirectory = [[FSDocumentsDirectory stringByAppendingPathComponent:@"Downloads"] copy];
    FSLibraryDirectory = [[homeDirectory stringByAppendingPathComponent:@"Library"] copy];
    FSTmpDownloadsDirectory = [[homeDirectory stringByAppendingPathComponent:@"tmp/WebDownloads"] copy];
    FSTmpArchiveDirectory = [[homeDirectory stringByAppendingPathComponent:@"tmp/FSArvhive"] copy];
    FSTmpUnarchiveDirectory = [[homeDirectory stringByAppendingPathComponent:@"tmp/FSUnarchive"] copy];
    FSTmpEmailDirectory = [[homeDirectory stringByAppendingPathComponent:@"tmp/FSEmail"] copy];
    
    theFileManager = [NSFileManager defaultManager];
    
    NSMainDateFormatter = [[NSDateFormatter alloc] init];
    [NSMainDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    UISettingsInitialize(); // must after initializing global variable
}

static void GlobalFinalize(void) {
    UISettingsFinalize(); // must before releasing global variable
    
    NSMainDateFormatter = nil;
    
    theFileManager = nil;
    
    FSDocumentsDirectory = nil;
    FSDownloadsDirectory = nil;
    FSLibraryDirectory = nil;
    FSTmpDownloadsDirectory = nil;
    FSTmpArchiveDirectory = nil;
    FSTmpUnarchiveDirectory = nil;
    FSTmpEmailDirectory = nil;
    
    UIFontBold10 = nil;
    UIFontBold12 = nil;
    UIFontBold14 = nil;
    UIFontBold16 = nil;
    UIFontBold18 = nil;
    UIFontNormal10 = nil;
    UIFontNormal12 = nil;
    UIFontNormal14 = nil;
    UIFontNormal16 = nil;
    
    CGColorBlack = NULL;
    CGColorClear = NULL;
    CGColorDarkGray = NULL;
    CGColorGray = NULL;
    CGColorLightGray = NULL;
    CGColorDarkCyan = NULL;
    CGColorPDFBackground = NULL;
    CGColorSelectedBackground = NULL;
    CGColorTexturedBackground = NULL;
    CGColorViewFlipsideBackground = NULL;
    CGColorWhite = NULL;
    
    UIColorBlack = nil;
    UIColorClear = nil;
    UIColorDarkGray = nil;
    UIColorGray = nil;
    UIColorLightGray = nil;
    UIColorDarkCyan = nil;
    UIColorPDFBackground = nil;
    UIColorSelectedBackground = nil;
    UIColorTexturedBackground = nil;
    UIColorViewFlipsideBackground = nil;
    UIColorWhite = nil;
    
    theApplication = nil;
}

@interface FWAppDelegate ()
@property (nonatomic) BOOL isDFU;
@property (nonatomic, strong) UIScrollView *guideView;
@end

NSString *SBGetUniqueName(void) {
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    const CFUUIDBytes uuidBytes = CFUUIDGetUUIDBytes(uuid);
    NSString *UUIDString = [GTMBase64 stringByWebSafeEncodingBytes:&uuidBytes length:sizeof(uuidBytes) padded:NO];
    
    CFRelease(uuid);
    
    return UUIDString;
}

@implementation FWAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [Bugly startWithAppId:@"0bea4798ce"];
    
    /* Log */
    [FSCLogExportManagerShared startLogRecord];

    GlobalInitialize(application);
    FWGlobalIntialize();
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [SVProgressHUD setMinimumDismissTimeInterval:2.0];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:[UIColor whiteColor]];
    [self.window makeKeyAndVisible];
    
    FWRootViewController *fwRootVC = [[FWRootViewController alloc] init];
    [self.window setRootViewController:fwRootVC];
    // 添加引导页
    [self show];
    
    // 检测App版本更新
    FBVersionCheck *versionCheck = [[FBVersionCheck alloc] init];
    [versionCheck checkForUpdate];
    
    return YES;
}

- (void)dealloc {
    GlobalFinalize();
}

- (void)setupUI {
    UIScrollView *guide = [[UIScrollView alloc] initWithFrame:self.window.frame];
    [self.window addSubview:guide];
    guide.backgroundColor = [UIColor clearColor];
    guide.contentSize = CGSizeMake(self.window.frame.size.width*3, 0);
    // 取消反弹
    guide.bounces = NO;
    // 隐藏滑动条
    guide.showsHorizontalScrollIndicator = NO;
    guide.showsVerticalScrollIndicator = NO;
    // 整页滚动
    guide.pagingEnabled = YES;
    
    NSArray *imageArr;
    if (kNavBar_Height == 88) {
        imageArr = @[@"Beacon_X",@"Setting_X",@"About_X"];
    } else {
        imageArr = @[@"Beacon",@"Setting",@"About"];
    }
    for (int i = 0; i < imageArr.count; i++) {
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(guide.frame.size.width*i, 0, guide.frame.size.width, guide.frame.size.height)];
        imageV.image = [UIImage imageNamed:imageArr[i]];
        [guide addSubview:imageV];
    }
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
    [btn sizeToFit];
    btn.center = CGPointMake(guide.frame.size.width*2.5, guide.frame.size.height*3/4.0);
    [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    btn.adjustsImageWhenHighlighted = NO;
    [guide addSubview:btn];
    self.guideView = guide;
    
}

- (void)click {
    __weak __typeof(self) weakSelf = self;
    
    [UIView animateWithDuration:1 animations:^{
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        
        strongSelf.guideView.transform = CGAffineTransformScale(self.guideView.transform, 3, 3);
        strongSelf.guideView.alpha = 0;
    } completion:^(BOOL finished) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        
        [strongSelf.guideView removeFromSuperview];
        strongSelf.guideView = nil;
    }];
}

- (void)show {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *currentVersion =[[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
    if (![user boolForKey:currentVersion]) { //显示引导页面 用version做对比
        [self setupUI];
        [user setBool:YES forKey:currentVersion];
        [user synchronize];
    }
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    if ([[url absoluteString] containsString:@"file"]) {
        NSString *fileName = [[url lastPathComponent] stringByRemovingPercentEncoding];
        NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/Inbox/%@", fileName];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:FWUpdateFilePathNotification object:nil userInfo:@{ @"url" : path }];
    }
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
