//
//  IntroViewController.m
//  kneet2
//
//  Created by Jason Lee on 9/16/15.
//  Copyright (c) 2015 Jason Lee. All rights reserved.
//
#import "RequestHandler.h"
#import "NetworkServiceHandler.h"
#import "CustomImageView.h"
#import "NSString-Addtions.h"
#import "PermissionGuidePopupView.h"
#import "IntroViewController.h"
#import "CustomDatePopupView.h"


@interface IntroViewController () <NetworkServiceHandlerDelegate> {
    
    NSDate *_elapsedDate;
    
}

@end

#pragma mark - Class Definition

@implementation IntroViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initUI];
    
    _elapsedDate = [NSDate systemDate];
    
    NSLog(@"%s\n applicationState = %zd", __PRETTY_FUNCTION__, [UIApplication sharedApplication].applicationState);
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
        [self prepareViewDidLoad];
    }
}


- (void)initUI {
    
    UIImage *splashImage = nil;
    CGRect screen = [UIScreen mainScreen].bounds;
    
    if (screen.size.height == 667.0f) {//iphone6
        splashImage = [UIImage imageNamed:@"Brand Assets-800-667h"];
    } else if (screen.size.height == 736.0f) {//iphone6 plus
        splashImage = [UIImage imageNamed:@"Brand Assets-800-Portrait-736h"];
    } else if (screen.size.height == 480) {//iphone4s
        splashImage = [UIImage imageNamed:@"Brand Assets-700"];
        if (!IS_IPAD) {
            _constraintLableLtdBottom = [_constraintLableLtdBottom setMutltiplier:0.833f];
        }
    } else {//iphone5 over
        splashImage = [UIImage imageNamed:@"Brand Assets-700-568h"];
    }
    
    [_imgvSplash setImage:splashImage];
}

- (void)prepareViewDidLoad {
    
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
//    if ([NetworkServiceHandler.handler startSearchBonjourServices])
//    {
//        NSLog(@"mdns 찾기");
//        NetworkServiceHandler.handler.delegate = self;
//    }
//    else
//    {
//        NSLog(@"mdns 찾기2");
//        [self requestVersionInfo];
//    }
    
    [self requestVersionInfo];
}

#pragma mark - Main Logic
- (NSInteger)elapsedSecondsFromNow {
    NSInteger seconds = 0;
    
    if (_elapsedDate) {
        NSTimeInterval elapsed = [[NSDate systemDate] timeIntervalSinceDate:_elapsedDate];
        seconds = elapsed;
    }
    return seconds;
}

- (void)requestVersionInfo {
    
    if ([self elapsedSecondsFromNow] < 2) {
        [self performSelector:@selector(requestVersionInfo) withObject:nil afterDelay:0.2f];
        return;
    }
    
    //parameters
    NSDictionary *parameter = @{@"os_type": MOBILE_DEVICE_TYPE,
                                @"store_code": APPSTORE_TYPE,
                                @"app_version": [CommonUtil applicationShortVersion]};
    
    NSString *path = [NSString stringWithFormat:API_POST_APP_VERSION];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        JDJSONModel *result = (JDJSONModel *) responseObject;
        
        if (result) {//API 성공 ,
            
            if ([result.resultCode isEqualToString:@"99"]) {//사용불가
                
                [[JDFacade facade] alertTitle:@"APP 업데이트"
                                      message:@"지금 업데이트하시겠습니까?"
                             completionHander:^{
                                 
                                 NSString *appURL = URL_APP_UPDATE;
                                 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]];
                                 
                             }];

            }
            else {

                NSString *check = [[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_PERMISSION_CHECK];
                
                if (check != nil && EQUALS(check, @"Y")) {

                    [self moveLogin];
                }
                else {

                    [self checkPermission];
                }
                
            }
        }
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)checkPermission {
    
    NSLog(@"checkPermission");

    PermissionGuidePopupView *popup = [[PermissionGuidePopupView alloc] initWithNibName:@"PermissionGuidePopupView" bundle:nil];
    [popup presentWithData:nil
                     owner:self
                     shown:^{
                         
                     } dismissed:^(NSInteger result, id data) {
                         
                         [[JDFacade facade] storeObjectToUserDefaults:@"Y"
                                                               forKey:USDEF_APP_PERMISSION_CHECK];
                         [self moveLogin];
                     }];
   
}

- (void)moveLogin {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"LoginViewController" storyboardName:@"Main"];
        [JDFacade facade].appDelegate.window.rootViewController = vc;
    });
}


#pragma mark - NetworkServiceHandler Delegate
- (void)didSucceedPublishService {
    
    [self requestVersionInfo];
}

- (void)didSucceedPublishService:(NSArray *)arrService
{
    [self requestVersionInfo];
    
    //NSLog(@"Result : %@", arrService);
    for (NSNetService *service in arrService) {
        NSDictionary* dict = [NSNetService dictionaryFromTXTRecordData:[service TXTRecordData]];
        SHOW_DICTIONARY_INFO(dict);


        NSLog(@"manufacturer : %@", [NSString stringWithUTF8Data:dict[@"model_number"]]);
//        [[JDFacade facade] alert:dict[@"manufacturer"]];
    }
    
    [NetworkServiceHandler.handler stopSearchBonjourServices];
    [self requestVersionInfo];
}

- (void)didFailPublishService:(id)errorInfo {
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, errorInfo);
    
    [self requestVersionInfo];
}

#pragma mark - MemoryWarning

- (void)viewDidDisappear:(BOOL)animated {
    NetworkServiceHandler.handler.delegate = nil;
}

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

@end
