//
//  LAVersion.m
//  LAVersion
//
//  Created by Luis Ascorbe on 21/12/12.
//  Copyright (c) 2012 Luis Ascorbe. All rights reserved.
//
/*
 
 LAVersion is available under the MIT license.
 
 Copyright © 2012 Luis Ascorbe.
 
 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 */

#import "LAVersion.h"

//#import "AFJSONRequestOperation.h"

@implementation NSString(LAVersion)

- (NSComparisonResult)compareVersion:(NSString *)version
{
    return [self compare:version options:NSNumericSearch];
}

- (NSComparisonResult)compareVersionDescending:(NSString *)version
{
    switch ([self compareVersion:version])
    {
        case NSOrderedAscending:
        {
            return NSOrderedDescending;
        }
        case NSOrderedDescending:
        {
            return NSOrderedAscending;
        }
        default:
        {
            return NSOrderedSame;
        }
    }
}

@end

@implementation LAVersion

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(DRLAVersion)

RCT_EXPORT_METHOD(checkAppStoreVersion:(BOOL)showMessage){
    [[LAVersion sharedInstance] checkAppVersion:showMessage];
}

static LAVersion *sharedInstance = nil;

+ (LAVersion *)sharedInstance
{
    if (sharedInstance == nil)
    {
        sharedInstance = [[self alloc] init];
    }
    return sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        //[self checkAppVersion:YES];
    }
    return self;
}

- (id)initShowMessage:(BOOL)showMessage
{
    self = [super init];
    if (self)
    {
        [self checkAppVersion:showMessage];
    }
    return self;
}

#if !__has_feature(objc_arc)
- (void)dealloc
{
    if (dicDatosApp != nil)
        
        [super dealloc];
}
#endif

- (void) checkAppVersion:(BOOL)showMessage
{
    // LAVersion works with the bundleID of the current app, you culd change it with the id of the app store with this link: http://itunes.apple.com/%@/lookup?id=[AppStoreID]
    // this example uses the AndryBirds's bundleID to show how it works.
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        
        NSString *urlBase = @"https://itunes.apple.com/lookup?id=597452467"; // http://itunes.apple.com/%@/lookup?id=%@
        NSString *url = [NSString stringWithFormat:urlBase, [[NSLocale preferredLanguages] objectAtIndex:0], [[NSBundle mainBundle] bundleIdentifier]];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSString *jsonString = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
        
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        
        if (!jsonData) {
            return ;
        }
        
        NSDictionary *dicJSON = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
        NSArray *arrResultados = [NSArray arrayWithArray:[dicJSON objectForKey:@"results"]];
        
        // compruebo que me haya devuelto resultados
        if ([arrResultados count] > 0)
        {
            dicDatosApp = [[NSDictionary alloc] initWithDictionary:[arrResultados objectAtIndex:0]];
            if ([dicDatosApp objectForKey:@"version"]) {
                newVersion = [dicDatosApp objectForKey:@"version"];
            }
            
            if ([dicDatosApp objectForKey:@"bundleId"])
            {
                NSString *applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                
                // compruebo si hay una version nueva
                if ([applicationVersion compareVersion:[dicDatosApp objectForKey:@"version"]] == NSOrderedAscending){
//                    if ([self.delegate respondsToSelector:@selector(laVersionNewVersionAvailable:)]){
//                        [self.delegate laVersionNewVersionAvailable:dicDatosApp];
//                    }
                    
                    if (showMessage)
                    {
                        // Hay nueva version
                        NSString *releaseNotes = [dicDatosApp objectForKey:@"releaseNotes"];
                        NSString *version = [dicDatosApp objectForKey:@"version"];
                        
                        NSString *neverUpdateVersionStr;
                        BOOL neverUpdate = NO;
                        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"newVersion"]) {
                            neverUpdateVersionStr = [NSString stringWithFormat:@"neverUpdateTo%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"newVersion"]];
                            if ([[NSUserDefaults standardUserDefaults] objectForKey:neverUpdateVersionStr]) {
                                neverUpdate = [[NSUserDefaults standardUserDefaults] boolForKey:neverUpdateVersionStr];
                            }
                        }
                        
                        if (!neverUpdate) {
//                            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"检测到新版本%@", version]
//                                                                                message:releaseNotes //[NSString stringWithFormat:NSLocalizedString(@"%@ \n\n Do you want update now?", @""), releaseNotes]
//                                                                               delegate:self
//                                                                      cancelButtonTitle:@"稍后再说"
//                                                                      otherButtonTitles:@"马上更新", @"忽略该版本", nil];
//                            [alertView show];
                            
                            //初始化提示框；
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"检测到新版本%@", version] message:releaseNotes preferredStyle:  UIAlertControllerStyleAlert];
                            
                            [alert addAction:[UIAlertAction actionWithTitle:@"稍后再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                //点击按钮的响应事件；
                            }]];
                            
                            [alert addAction:[UIAlertAction actionWithTitle:@"马上更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                //点击按钮的响应事件；
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[dicDatosApp objectForKey:@"trackViewUrl"]]];
                            }]];
                            
                            [alert addAction:[UIAlertAction actionWithTitle:@"忽略该版本" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                //点击按钮的响应事件；
                                if ([[NSUserDefaults standardUserDefaults] objectForKey:@"newVersion"]) {
                                    NSString *str = [NSString stringWithFormat:@"neverUpdateTo%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"newVersion"]];
                                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:str];
                                }
                            }]];
                            
                            //弹出提示框；  
                            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:true completion:nil];
                        }
                    }else{
                        if (sharedInstance){
                            sharedInstance = nil;
                        }
                    }
                }else{
                    //                        NSLog(@"LAVersion without results");
                }
            }else{
                //                    NSLog(@"LAVersion could not find this application on iTunes");
            }
        }
    });
}

- (void)willPresentAlertView:(UIAlertView *)alertView{
    if (alertView.subviews.count >= 3) {
        UIView * view = [alertView.subviews objectAtIndex:2];
        if([view isKindOfClass:[UILabel class]]){
            UILabel* label = (UILabel*) view;
            label.textAlignment = NSTextAlignmentLeft;
        }
    }
}


@end
