//
//  EquipmentFileUploader.m
//  EC145Gen
//
//  Created by Vadim on 5/5/14.
//
//

#import "EquipmentFileUploader.h"

@implementation EquipmentFileUploader {
    NSString* uploadURL_;
    NSString* downloadURL_;
}

- (id)initWithUploadURL:(NSString *)uploadURL andDownloadURL:(NSString *)downloadURL {
    self = [super init];
    if (self) {
        downloadURL_ = downloadURL;
        uploadURL_ = uploadURL;
    }
    return self;
}

- (void)downloadToFile:(NSString *)fileName withCompletionBlock:(void (^)(bool, NSString *))block {
    // NSData downloads any file from an URL
    
    //NSLog(@"EquipmentFileUploader ********************");
    
    NSString* urlstring=[downloadURL_ stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSString *content=[NSString stringWithCString:[data bytes] encoding:NSUTF8StringEncoding];
            if ([content isEqualToString:@"NOK"]) {
                //NSLog(@"error NOK");
                block(false, @"FleetControl Code or Callsign not found.");
                
            } else if ([content isEqualToString:@"NOK2"]) {
                NSLog(@"error NOK2");
                block(false, @"no data for this helicopter found on server.");
                
            } else {
                //NSLog(@"EquipmentFileUploader writeToFile");
                [data writeToFile:fileName atomically:YES];
                block(true, nil);
                
            }
        } else {
             
            block(false, [error localizedDescription]);
        }
    }];
    
    [dataTask resume];
}


- (void)uploadFile:(NSString *)fileName withCompletionBlock:(void (^)(bool, NSString *))block {
    //create url
    NSString* url=[uploadURL_ stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding];
    NSLog(@"url: %@",url);
    
    NSData *myData = [NSData dataWithContentsOfFile:fileName];
    
    
    NSURLRequest *urlRequest = [self postRequestWithURL:url
                                                   data:myData
                                               fileName:[fileName lastPathComponent]];
    NSURLSessionDataTask* dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *responseString =[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        if ([responseString isEqualToString:@"OK"]) {
            
            block(true, nil);
                                
        } else if ([responseString isEqualToString:@"NOK1"]) {
            block(false,@"FleetControl could not save your data.");
        } else if ([responseString isEqualToString:@"NOK2"]) {
            block(false,@"The helicopter is not part of your FleetControl fleet.");
        }
    }];
    
    [dataTask resume];
}



-(NSURLRequest *)postRequestWithURL: (NSString *)url
                               data: (NSData *)data
                           fileName: (NSString*)fileName
{
    
    //NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
    [urlRequest setURL:[NSURL URLWithString:url]];
    [urlRequest setHTTPMethod:@"POST"];
    
    NSString *myboundary = [NSString stringWithFormat:@"%@",@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",myboundary];
    [urlRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *postData = [NSMutableData data]; //[NSMutableData dataWithCapacity:[data length] + 512];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", myboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:@"%@",@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[NSData dataWithData:data]];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", myboundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [urlRequest setHTTPBody:postData];
    return urlRequest;
}


@end