//
//  HTTPRequest.m
//  SKCore
//
//  Created by jungeol.park on 2014. 9. 25..
//  Copyright (c) 2014 ACCVUER. All rights reserved.
//

#import "HTTPRequest.h"

#define TRANSFER_REQUEST_DELAY 1
#define TRANSFER_WAITING_QUEUE_UNKNOW_POSITION -2

@implementation HTTPRequest

-(id)init
{
    self = [super init];
    if(self)
    {
        m_serverAdd = [[SKAAppDelegate getAppDelegate] amdGetClosestTarget];
        m_port = [[SKAAppDelegate getAppDelegate].testSchedule_new getTransferTestPort];
        m_needStopRequestWaitingQueue = NO;
    }
    return self;
}

#pragma mark - request transfer waiting queue
-(void)requestTransferWaitingQueue
{
    NSMutableString *urlString = [[NSMutableString alloc] init];
    if (![m_serverAdd hasPrefix:@"http"])
    {
        [urlString appendString:@"http://"];
    }
    [urlString appendString:m_serverAdd];
    [urlString appendString: [NSString stringWithFormat:@":%@", m_port]];
    [urlString appendString:@"/q"];
    
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
                                                                cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                            timeoutInterval:10];
    [request setHTTPMethod:@"GET"];
    
    NSString *cookieStr = [SKGlobalMethods makeCookieValueOfHeaderByURL:url];
    [request setValue:cookieStr forHTTPHeaderField:@"Cookie"];
    
    NSOperationQueue *idQueue = [[NSOperationQueue alloc] init];
    [idQueue setName:@"transferWaitingQueue"];
    
    if(m_needStopRequestWaitingQueue)
        return;
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [NSURLConnection sendAsynchronousRequest:request queue:idQueue completionHandler:^(NSURLResponse *response,
                                                                                       NSData *data,
                                                                                       NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             
             [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//             SK_ASSERT_NONSERROR(error);

             if(m_needStopRequestWaitingQueue)
                 return;
             
             TransferWaitingQueueErrorType errorType;
             
             do{
                 if (error != nil)
                 {
                     errorType = TransferWaitingQueueErrorType_ConnectionError;
                     break;
                 }
                 
                 if (response == nil)
                 {
                     errorType = TransferWaitingQueueErrorType_NoResponseDataError;
                     break;
                 }
                 
                 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
                 
                 if (httpResponse.statusCode == 200)
                 {
                     if (data != nil)
                     {
#ifdef DEBUG
                         {
                             NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookiesForURL:[url absoluteURL]];
                             NSLog(@"########## %@", cookies);
                             NSLog(@"@@@@@@@ dddd %@", [[httpResponse allHeaderFields] description]);
                         }
#endif
                         NSDictionary *dic = [SKGlobalMethods dicFromJsonData:data];
                         if(dic == nil || dic.count == 0)
                         {
                             errorType = TransferWaitingQueueErrorType_JSONParsingError;
                             break;
                         }

                         errorType = TransferWaitingQueueErrorType_None;
                         NSInteger waitingQueuePosition = [[dic valueForKey:@"q"] integerValue];
                         
                         if([self.delgate respondsToSelector:@selector(didReceiveTransferWaitingQueueResponsWithPosition:withError:)])
                             [self.delgate didReceiveTransferWaitingQueueResponsWithPosition:waitingQueuePosition
                                                                                   withError:errorType];
                         
                         if(waitingQueuePosition != 0)
                         {
                             [self performSelector:@selector(retryRequestWaitingQueueWithPosition:)
                                        withObject:[NSNumber numberWithInteger:waitingQueuePosition]
                                        afterDelay:TRANSFER_REQUEST_DELAY];
                         }
                     }
                     else
                     {
                         errorType = TransferWaitingQueueErrorType_NoResponseDataError;
                     }
                 }
                 else
                 {
                     errorType = TransferWaitingQueueErrorType_StatusCodeError;
                 }
             }while (NO);
             
             // error handle
             if(errorType != TransferWaitingQueueErrorType_None)
             {
                 if([self.delgate respondsToSelector:@selector(didReceiveTransferWaitingQueueResponsWithPosition:withError:)])
                     [self.delgate didReceiveTransferWaitingQueueResponsWithPosition:TRANSFER_WAITING_QUEUE_UNKNOW_POSITION
                                                                           withError:errorType];
                 
                 [self performSelector:@selector(retryRequestWaitingQueueWithPosition:)
                            withObject:[NSNumber numberWithInteger:TRANSFER_WAITING_QUEUE_UNKNOW_POSITION]
                            afterDelay:TRANSFER_REQUEST_DELAY];
             }
         });
     }];
}

-(void)retryRequestWaitingQueueWithPosition:(NSNumber *)q_position
{
    if(m_needStopRequestWaitingQueue)
        return;
    
    int position = [q_position intValue];
    
    if(position == 0)
    {
        // do not need retry
    }
    else
    {
        [self requestTransferWaitingQueue];
    }
}

-(void)stopRequestTransferWaitingQueue
{
    m_needStopRequestWaitingQueue = YES;
}

#pragma mark - request end transfer session
-(void)requestEndTransferSession
{
    NSMutableString *urlString = [[NSMutableString alloc] init];
    if (![m_serverAdd hasPrefix:@"http"])
    {
        [urlString appendString:@"http://"];
    }
    [urlString appendString:m_serverAdd];
    [urlString appendString: [NSString stringWithFormat:@":%@", m_port]];
    [urlString appendString:@"/e"];
    
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
                                                                cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                            timeoutInterval:10];
    [request setHTTPMethod:@"GET"];
    
    NSString *cookieStr = [SKGlobalMethods makeCookieValueOfHeaderByURL:url];
#ifdef DEBUG
    NSLog(@"end transfer session cookie = %@", cookieStr);
#endif
    [request setValue:cookieStr forHTTPHeaderField:@"Cookie"];
    
    NSOperationQueue *idQueue = [[NSOperationQueue alloc] init];
    [idQueue setName:@"endTransferSession"];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [NSURLConnection sendAsynchronousRequest:request queue:idQueue completionHandler:^(NSURLResponse *response,
                                                                                       NSData *data,
                                                                                       NSError *error)
     {
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
         
         if (error != nil || response == nil)
         {
             NSLog(@"endTransferSession request error");
             return;
         }
         
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
         
         if (httpResponse.statusCode == 200)
         {
             NSLog(@"endTransferSession success");
             return;
         }
         else
         {
             NSLog(@"endTransferSession statusCode not 200");
             return;
         }
     }];
}
@end
