//
//  ViewController.m
//  Siberian Angular
//
//  Created by Adrien Sala on 08/07/2014.
//  Copyright (c) 2014 Adrien Sala. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize webView, locationManager, loader;
@synthesize splashScreen, splashScreenImage;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    webViewIsLoaded = NO;
    
    [self addSplashScreen];
    
    // Créé et affiche le loader
    CGRect frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
    loader = [[loaderView alloc] initWithFrame:frame];
    // Ajoute le loader à la vue en cours
    [self.view addSubview:loader];
    [self.view bringSubviewToFront:loader];
    [loader show];
    
    webView.delegate = self;
    webView.scrollView.bounces = NO;
    
    [self loadWebview];
}

- (void)viewDidUnload {
    [self setWebView:nil];
    [self setLocationManager:nil];
    [super viewDidUnload];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addSplashScreen {
    
    splashScreen = [UIImageView alloc];
    
    if(splashScreenImage) {
        splashScreen = [splashScreen initWithImage:splashScreenImage];
    } else if(isScreeniPhone6Plus()) {
        splashScreen = [splashScreen initWithImage:[UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"]];
    } else if(isScreeniPhone6()) {
        splashScreen = [splashScreen initWithImage:[UIImage imageNamed:@"LaunchImage-800-667h@2x"]];
    } else if(isScreeniPhone5()) {
        splashScreen = [splashScreen initWithImage:[UIImage imageNamed:@"LaunchImage-700-568h@2x"]];
    } else {
        splashScreen = [splashScreen initWithImage:[UIImage imageNamed:@"LaunchImage-700@2x"]];
    }
    
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    
    splashScreen.frame = CGRectMake(0, isAtLeastiOS7()?0:-19, screenBounds.size.width, screenBounds.size.height);
    
    [self.view addSubview:splashScreen];
    [self.view bringSubviewToFront:splashScreen];

}

- (void)loadWebview {
    
    NSString *url = [[Url sharedInstance] get:@""];
    NSURLRequest *request = [NSURLRequest requestWithURL:[[NSURL alloc] initWithString:url]];
    
    [webView loadRequest:request];
    
}

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *url = [NSString stringWithFormat:@"%@", [request URL]];
    NSLog(@"url : %@", url);
    if([url hasPrefix:@"mailto:"]) {
        return YES;
    } else if([url rangeOfString:@"tel:"].location != NSNotFound) {
        NSLog(@"phone number : %@", [request URL]);
    } else if(navigationType == UIWebViewNavigationTypeLinkClicked || ([url hasPrefix:@"https://m.facebook.com/"] && [[[request URL] path] hasSuffix:@"/dialog/oauth"])) {
        webviewUrl = [[NSURL alloc] initWithString:url];
        [self performSegueWithIdentifier:@"openWebview" sender:self];
        return NO;
    } else if([url rangeOfString:@"app:"].location != NSNotFound) {

        NSLog(@"Detecting Function");
        NSArray *words = [url componentsSeparatedByString:@":"];
        SEL function = NSSelectorFromString([words lastObject]);
        NSLog(@"Function: %@", [words lastObject]);
        if([self respondsToSelector:function]) {
            NSLog(@"Function Found: %@", [words lastObject]);
            [self performSelector:function];
        }

        return NO;

    }

    return YES;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"Error when loading the content");
    if(!useCache) {
        useCache = true;
        [self loadWebview];
    }
    [loader hide];
}

- (void)webViewDidFinishLoad:(UIWebView *)wv {
    if(isAtLeastiOS7()) {
        [webView stringByEvaluatingJavaScriptFromString:@"angular.element(document.body).addClass('iOS7')"];
    }

    NSUserDefaults *dict = [NSUserDefaults standardUserDefaults];
    NSString *identifier = [dict stringForKey:@"identifier"];
    NSString *jsSetIdentifier = [NSString stringWithFormat:@"if(window.Application) window.Application.device_uid = '%@'", identifier];
    [webView stringByEvaluatingJavaScriptFromString:jsSetIdentifier];

    NSString *jsonString = [webView stringByEvaluatingJavaScriptFromString:@"JSON.stringify(window.colors)"];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *colors = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    [common setColors:colors];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"openWebview"]) {
        [segue.destinationViewController setWebViewUrl:webviewUrl];
    }
}


- (void)getLocation {
    
    NSLog(@"locationServicesEnabled: %@", [CLLocationManager locationServicesEnabled] ? @"YES":@"NO");
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    locationManager.delegate = self;
    
    if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [locationManager requestWhenInUseAuthorization];
    } else {
        [locationManager startUpdatingLocation];
    }
}

- (void)appIsLoaded {
    
    [loader hide];
    
    if(splashScreen.hidden == NO) {
        // Initialisation et animation du splashscreen
        [UIView beginAnimations:@"startup_image" context:nil];
        [UIView setAnimationDuration:0.8];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector (startupAnimationDone:finished:context:)];
        splashScreen.alpha = 0;
        [UIView commitAnimations];
    }

}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    NSLog(@"didChangeAuthorizationStatus: %d", status);
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusAuthorized) {
        // iOS 7 will redundantly call this line.
        [self.locationManager startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        NSLog(@"kCLAuthorizationStatusNotDetermined");
        [webView stringByEvaluatingJavaScriptFromString:@"setCoordinates('error')"];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)location {
    CLLocation *currentLocation = [location objectAtIndex:0];
    [locationManager stopUpdatingLocation];
    NSLog(@"position: %@", currentLocation);
    NSString *coordinates = [[NSString alloc] initWithFormat:@"setCoordinates('success', %f, %f)", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude];
    [webView stringByEvaluatingJavaScriptFromString:coordinates];
    
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [locationManager stopUpdatingLocation];
    NSLog(@"position: %@", newLocation);
    NSString *coordinates = [[NSString alloc] initWithFormat:@"setCoordinates('success', %f, %f)", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
    [webView stringByEvaluatingJavaScriptFromString:coordinates];
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [webView stringByEvaluatingJavaScriptFromString:@"setCoordinates('error')"];
    NSLog(@"Can't access user's position");
}

- (void)removeBadge {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)startupAnimationDone:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    
    [splashScreen removeFromSuperview];

}


@end
