//
//  ICRURLProtocol.m
//  XFFruit
//
//  Created by Xummer on 15/4/13.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRURLProtocol.h"
#import "ICRHTTPController.h"

@interface ICRURLProtocol ()
@property (nonatomic, readwrite, strong) NSURLConnection *connection;
@end

@implementation ICRURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    // IPatrol/rest/attachment/downloadDirect/id
    // -[NSURL pathComponents] = @["/", "IPatrol", "rest", "attachment", "downloadDirect", "file.html"] (note that the initial / is part of it)
    
    NSArray *pathComponents = [request.URL pathComponents];
    if ([pathComponents count] < 5) {
        return NO;
    }
    
    if ([pathComponents[ 1 ] isEqualToString:@"IPatrol"] &&
        [pathComponents[ 2 ] isEqualToString:@"rest"] &&
        [pathComponents[ 3 ] isEqualToString:@"attachment"] &&
        [pathComponents[ 4 ] isEqualToString:@"downloadDirect"] )
    {
        NSSet *trackMethods = [NSSet setWithObjects:@"GET", @"POST", nil];
        
        NSURL *httpUrl = [NSURL URLWithString:HTTP_REST_API_BASE_URL];
        if ([[request.URL host] isEqualToString:[httpUrl host]] &&
            [trackMethods containsObject:[[request HTTPMethod] uppercaseString]] &&
            ![request valueForHTTPHeaderField:@"token"] &&
            ([[request.URL scheme] caseInsensitiveCompare:@"http"] == NSOrderedSame ||
             [[request.URL scheme] caseInsensitiveCompare:@"https"] == NSOrderedSame)) {
                return YES;
            }
    }
    
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a
                       toRequest:(NSURLRequest *)b
{
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading {
    // Set Auth
    NSURLRequest *connectionRequest = [self updateAuthForHTTPRequest:self.request];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:connectionRequest
                                                                delegate:self];
    self.connection = connection;
}

- (void)stopLoading {
    [self.connection cancel];
    self.connection = nil;
}

#pragma mark - Private Method
- (NSURLRequest *)updateAuthForHTTPRequest:(NSURLRequest *)request {
    NSString *nsAuthData = [[ICRUserUtil sharedInstance] token];
    
    if (nsAuthData) {
        
        NSMutableURLRequest *mutableReq = [request mutableCopy];
        
        [mutableReq setValue:nsAuthData forHTTPHeaderField:@"token"];
        [mutableReq setValue:nil forHTTPHeaderField:@"Accept"];
        
        return mutableReq;
    }
    
    return request;
}

#pragma mark -

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    [self.client URLProtocol:self
            didFailWithError:error];
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    if (response != nil)
    {
        [[self client] URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
    }
    return request;
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
    return YES;
}

- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [self.client URLProtocol:self
didReceiveAuthenticationChallenge:challenge];
}

- (void)connection:(NSURLConnection *)connection
didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [self.client URLProtocol:self
didCancelAuthenticationChallenge:challenge];
}


- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
    [self.client URLProtocol:self
          didReceiveResponse:response
          cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data
{
    [self.client URLProtocol:self
                 didLoadData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    return cachedResponse;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.client URLProtocolDidFinishLoading:self];
}

@end
