//
//  IntroViewController.m
//  kneet2
//
//  Created by Jason Lee on 9/16/15.
//  Copyright (c) 2015 Jason Lee. All rights reserved.
//
#import "RequestHandler.h"
#import "IntroViewController.h"


@interface IntroViewController () <NSNetServiceBrowserDelegate, NSNetServiceDelegate> {
    NSNetServiceBrowser *_netServiceBrowser;
    BOOL _isNotFirstLoading;
}

@property (weak, nonatomic)  NSNetService *netService;
@end

#pragma mark - Class Definition

@implementation IntroViewController


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


- (void)initUI {
    NSString *test = @"test";
    
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, test);
    DDLogError(@"test colors");
}

- (void)prepareViewDidLoad {
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
    [self requestBonjourList];
    
    
//#ifndef PRODUCT_MODE
//    
//    ServerPopTableView *spopup = [[ServerPopTableView alloc] initFromNib];
//    [spopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
//        if (buttonIndex == 0) {//OK
//            [self performSelector:@selector(requestVersionInfo) withObject:nil afterDelay:0.0f];
//        }
//    }];
//    
//#else
//    
//    [self performSelector:@selector(requestVersionInfo) withObject:nil afterDelay:0.0f];
//#endif
}

#pragma mark - Main Logic

- (void)requestBonjourList {
    
    if (_netServiceBrowser) {
        [_netServiceBrowser stop];
        _netServiceBrowser = nil;
    }
    
    _netServiceBrowser = [[NSNetServiceBrowser alloc] init];
    _netServiceBrowser.delegate = self;
    
    NSString *browseType;
    if (_netService == nil) {
        browseType = @"_services._dns-sd._udp.";
        self.title = @"mDNS";
    } else {
        NSString *fullDomainName = [NSString stringWithFormat:@"%@.%@", _netService.name, _netService.type];
        NSArray *domainNameParts = [fullDomainName componentsSeparatedByString:@"."];
        
        browseType = [NSString stringWithFormat:@"%@.%@.", [domainNameParts objectAtIndex:0], [domainNameParts objectAtIndex:1]];
        self.title = _netService.name;
    }
    [_netServiceBrowser searchForServicesOfType:browseType inDomain:@""];
}


- (void)requestVersionInfo {
    
    //parameters
    NSDictionary *parameter = @{@"os_type": MOBILE_DEVICE_TYPE,
                                @"store_code": APPSTORE_TYPE,
                                @"app_version": [CommonUtil applicationShortVersion]};
    
    NSString *path = [NSString stringWithFormat:API_GET_APP_VERSION];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath: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] alert:MSG_ALERT_APP_UPDATE completionHander:^{
                    NSString *appURL = URL_APP_UPDATE;
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]];
                }];
            } else {
                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;
                });
            }
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark NSNetServiceBrowserDelegate methods
-(void)netServiceBrowser:(NSNetServiceBrowser *)browser didNotSearch:(NSDictionary *)errorDict {
    _netServiceBrowser.delegate = nil;
    [_netServiceBrowser stop];
}

-(void)netServiceBrowserDidStopSearch:(NSNetServiceBrowser *)browser {
    _netServiceBrowser.delegate = nil;
}

-(void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing {
    if (!_isNotFirstLoading) {
        [self performSelector:@selector(requestVersionInfo) withObject:nil afterDelay:0.0f];
        _isNotFirstLoading = YES;
    }
    [_netService stop];
    
    
    
//    [_serviceArray addObject:aNetService];
//    
//    if (moreComing == NO) {
//        [self.tableView reloadData];
//        
//        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//        [_serviceArray sortUsingDescriptors:[NSArray arrayWithObject:sd]];
//        
//        //        self.netServiceBrowser.delegate = nil;
//        //        [self.netServiceBrowser stop];
//        //        self.netServiceBrowser  = nil;
//        NSRange stringRange = [self.title rangeOfString:@"mDNS"];
//        if (stringRange.location == 0) {
//            self.title = [NSString stringWithFormat:@"mDNS (%lu)", (unsigned long)[_serviceArray count]];
//        }
//    }
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didRemoveService:(NSNetService *)netService moreComing:(BOOL)moreComing {
//    for (int i = 0; i < _serviceArray.count; i++) {
//        if ([((NSNetService *)[_serviceArray objectAtIndex:i]).name isEqualToString:netService.name]) {
//            [_serviceArray removeObjectAtIndex:i];
//            break;
//        }
//    }
//    if (moreComing == NO) {
//        [self.tableView reloadData];
//        
//        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//        [_serviceArray sortUsingDescriptors:[NSArray arrayWithObject:sd]];
//        
//        NSRange stringRange = [self.title rangeOfString:@"mDNS"];
//        if (stringRange.location == 0) {
//            self.title = [NSString stringWithFormat:@"mDNS (%lu)", (unsigned long)[_serviceArray count]];
//        }
//    }
}

#pragma mark -
#pragma mark NSNetServiceDelegate methods
-(void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict {
    NSNumber *errorCode = [errorDict valueForKey:NSNetServicesErrorCode];
    
    NSString *errorMessage;
    switch ([errorCode intValue]) {
        case NSNetServicesActivityInProgress:
            errorMessage = @"서비스에 연결중입니다. 잠시 기다려 주세요.";
            //            errorMessage = @"Service Resolution Currently in Progress. Please Wait.";
            break;
        case NSNetServicesTimeoutError:
            errorMessage = @"서비스에 연결할 수 없습니다.";
            //            errorMessage = @"Service Resolution Timeout";
            [sender stop];
            break;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"mDNS Browser" message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

-(void)netServiceDidResolveAddress:(NSNetService *)service {
//    mDNSDetailViewController *sdvc = [self.storyboard instantiateViewControllerWithIdentifier:@"mDNSDetailViewController"];
//    sdvc.selectedService = service;
//    
//    [self.navigationController pushViewController:sdvc animated:YES];
}


#pragma mark - MemoryWarning
- (void)viewDidDisappear:(BOOL)animated {
    [_netServiceBrowser stop];
}

#pragma mark - UI Events



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

@end