//
//  KBYTDownloadStream.m
//  Seas0nPass
//
//  Created by Kevin Bradley on 3/9/07.
//  Copyright 2007 nito, LLC. All rights reserved.
//

#import <Foundation/Foundation.h>
/*
 
 class adapted from hawkeye's KBYTDownloadStream class for downloading youtube files, largely pruned to remove irrelevant sections + updated to cancel the xfer + remodified/updated to use blocks instead of antiquated delegate methods.
 
 */

#import "KBDownloadFile.h"


@implementation KBDownloadFile

@synthesize downloadLocation;

#pragma mark -
#pragma mark •• URL code

- (void)dealloc
{
	downloadLocation = nil;
}

- (void)cancel
{
    NSError *theError = nil;
	[self download:urlDownload didFailWithError:theError];
	[urlDownload cancel];
}


- (long long)updateFrequency
{
	return updateFrequency;
}

- (void)setUpdateFrequency:(long long)newUpdateFrequency
{
	updateFrequency = newUpdateFrequency;
}

- (id)init
{
	if(self = [super init]) {
        [self setUpdateFrequency:1];
        
	}
	
	return self;
}


- (void)downloadURL:(NSURL *)url toLocation:(NSString *)dlLocation
		   progress:(DownloadProgressBlock)progressBlock
		  completed:(DownloadCompletedBlock)completedBlock
{
	self.CompletedBlock = completedBlock;
	self.ProgressBlock = progressBlock;
	self.downloadLocation = dlLocation;

	NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"com.nito.installer"];
	
	// Creating sessions
	NSOperationQueue *operationQueue = [NSOperationQueue mainQueue];
	
	NSURLSession *backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:operationQueue];
	NSURLSessionDownloadTask *downloadTask = [backgroundSession downloadTaskWithURL:url];
	[downloadTask resume];
	
	
}

- (void)URLSession:(NSURLSession *)session
	  downloadTask:(NSURLSessionDownloadTask *)downloadTask
	  didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
	//NSLog(@"Session %@ download task %@ wrote an additional %lld bytes (total %lld bytes) out of an expected %lld bytes.\n", session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
	if (totalBytesExpectedToWrite != NSURLResponseUnknownLength) {
		
		double percentComplete=(totalBytesWritten/(float)totalBytesExpectedToWrite)*100.0;
		// NSLog(@"Percent complete - %f",percentComplete);
		
		if((freq%updateFrequency) == 0){
			
			if (self.ProgressBlock != nil)
			{
				self.ProgressBlock(percentComplete);
			}
			
			if (self.FancyProgressBlock != nil)
			{
				NSString *mediaType = @"media";
				NSString *pathExt = downloadLocation.pathExtension;
				if ([pathExt isEqualToString:@"m4v"])
				{
					mediaType = @"video";
				} else if ([pathExt isEqualToString:@"aac"])
				{
					mediaType = @"audio";
				}
				self.FancyProgressBlock(percentComplete, [NSString stringWithFormat:@"Downloading %@ file...", mediaType]);
			}
		}
		freq++;
		
	} else {
		
		NSLog(@"Bytes received - %lld",totalBytesWritten);
		
	}
	
	
}

- (void)URLSession:(NSURLSession *)session
	  downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
	NSLog(@"Session %@ download task %@ resumed at offset %lld bytes out of an expected %lld bytes.\n", session, downloadTask, fileOffset, expectedTotalBytes);
}

- (void)URLSession:(NSURLSession *)session
	  downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
	NSLog(@"Session %@ download task %@ finished downloading to URL %@\n", session, downloadTask, location);
	
	// Perform the completion handler for the current session
	//self.completionHandlers[session.configuration.identifier]();
	
	// Open the downloaded file for reading
	//NSError *readError = nil;
	//NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:location error:&readError];
	// ...
	
	// Move the file to a new URL
	NSFileManager *fileManager = [NSFileManager defaultManager];
	//NSURL *cacheDirectory = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject];
	NSError *moveError = nil;
	if ([fileManager fileExistsAtPath:self.downloadLocation])
	{
		[fileManager removeItemAtPath:self.downloadLocation error:nil];
	}
	if ([fileManager moveItemAtPath:location.path toPath:self.downloadLocation error:&moveError])
	{
		self.CompletedBlock(self.downloadLocation);
	} else {
		NSLog(@"error: %@", moveError);
	}
	/*
	if ([fileManager moveItemAtURL:location toURL:cacheDirectory error:&moveError]) {
		// ...
	}
	 */
}

//deprecated / obsolete, SHOULD still work but should never be used.
- (void)downloadFileWithURL:(NSURL *)url
                 toLocation:(NSString *)dlLocation
                   progress:(DownloadProgressBlock)progressBlock
                  completed:(DownloadCompletedBlock)completedBlock
{
    self.CompletedBlock = completedBlock;
    self.ProgressBlock = progressBlock;
    self.downloadLocation = dlLocation;
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    urlDownload = [[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
    [urlDownload setDestination:downloadLocation allowOverwrite:YES];
 
}


- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error

{
	NSLog(@"error: %@", error);
	//[handler downloadFailed:downloadLocation];
}

- (void)downloadDidFinish:(NSURLDownload *)download
{
   if(download == urlDownload) {
       
  
       if (self.CompletedBlock != nil)
       {
           self.CompletedBlock(downloadLocation);
       }
	}

}

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response

{
    bytesReceived=0;
    [self setDownloadResponse:response];
}

- (void)setDownloadResponse:(NSURLResponse *)response
{
	myResponse = response;
}

- (NSURLResponse *)downloadResponse
{
    return myResponse;
}

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length

{
    long long expectedLength = [[self downloadResponse] expectedContentLength];
    bytesReceived=bytesReceived+length;
    
    if (expectedLength != NSURLResponseUnknownLength) {
        
        double percentComplete=(bytesReceived/(float)expectedLength)*100.0;
       // NSLog(@"Percent complete - %f",percentComplete);
		
		if((freq%updateFrequency) == 0){
	        
            if (self.ProgressBlock != nil)
            {
                self.ProgressBlock(percentComplete);
            }
            
            if (self.FancyProgressBlock != nil)
            {
                NSString *mediaType = @"media";
                NSString *pathExt = downloadLocation.pathExtension;
                if ([pathExt isEqualToString:@"m4v"])
                {
                    mediaType = @"video";
                } else if ([pathExt isEqualToString:@"aac"])
                {
                    mediaType = @"audio";
                }
                self.FancyProgressBlock(percentComplete, [NSString stringWithFormat:@"Downloading %@ file...", mediaType]);
            }
		}
		freq++;
	    
    } else {
        
        NSLog(@"Bytes received - %f",bytesReceived);
        
    }
	
}
@end
