//
//  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 (strong, 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 publishNetService];
}

#pragma mark - Main Logic

- (void)publishNetService {
    _netService = [[NSNetService alloc] initWithDomain:@"" type:@"_ntels._tcp" name:[JDFacade facade].deviceHostName port:7979];
    if (_netService) {
        _netService.delegate = self;
        [_netService publish];
        
    } else {
        NSLog(@"An error occurred initializing the NSNetService object.");
    }
}

- (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],
                                @"service_id": MOBILE_SERVICE_ID};
    
    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 - NSNetServiceDelegate methods

- (void)netServiceDidPublish:(NSNetService *)sender {
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, sender);
    
    if (!_isNotFirstLoading) {
        [self performSelector:@selector(requestVersionInfo) withObject:nil afterDelay:0.0f];
        _isNotFirstLoading = YES;
    }
}

- (void)netServiceWillPublish:(NSNetService *)sender {
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, sender);
    
}

- (void)netServiceDidStop:(NSNetService *)sender {
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, sender);
    
}

- (void)netService:(NSNetService *)sender didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream {
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, sender);
    
}

- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary<NSString *,NSNumber *> *)errorDict {
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, errorDict);
}

- (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