//
//  IconDownloader.m
//  Allzic
//
//  Created by Alia Bourouis on 13/03/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "IconDownloader.h"

@implementation IconDownloader

@synthesize appIcon,indexPathInTableView,delegate,activeDownload,imageConnection,iconUrl;

#pragma mark

- (id)init {
	
	self = [super init];
	if (self != nil) {
	}
	return self;
}

- (void)startDownloadAtUrl:(NSString *)url withMaxSize:(CGFloat)maxSize {
    
    maxPictureSize          = maxSize;
	appIcon					= nil;
    iconUrl                 = url;
    self.activeDownload		= [NSMutableData data];
	self.imageConnection	= [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self];
	//NSLog(@"IconDownload at url index : %d with url : '%@'",indexPathInTableView.row,url);
}


- (void)cancelDownload {
	
    if (imageConnection != nil) {
        [self.imageConnection cancel];
        self.imageConnection = nil;
        self.activeDownload = nil;
    }
}


#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response {
    
    //NSLog(@"didReceiveResponse");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    //NSLog(@"didReceiveData");
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    self.activeDownload		= nil;
    self.imageConnection	= nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	//NSLog(@"connectionDidFinishLoading - index %d",indexPathInTableView.row);
    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
    CGFloat thumWidth;
    CGFloat thumHeight;
    if (image.size.width > image.size.height) {
        thumWidth = (maxPictureSize / image.size.width) * image.size.width;
        thumHeight = (maxPictureSize / image.size.width) * image.size.height;
    } else {
        thumWidth = (maxPictureSize / image.size.height) * image.size.width;
        thumHeight = (maxPictureSize / image.size.height) * image.size.height;
    }
    if (image.size.width > maxPictureSize || image.size.height > maxPictureSize) {
        CGSize itemSize = CGSizeMake(thumWidth, thumHeight);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [image drawInRect:imageRect];
        self.appIcon = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } else {
        self.appIcon = image;
    }
    self.activeDownload = nil;
    self.imageConnection = nil;
    [delegate appImageDidLoad:self];
}

@end
