/*
** AqRemoteFile
** 
** CHANGES:
** 0.1  (pozytron) Added code to turn off ID3 song titles, album data
** 0.21 (pozytron) New image
*/

#import "AqCoreController.h"
#import "AqRemoteFile.h"
#import "DWByteSize.h"
#import "DWCachedString.h"
#import "DWTableString.h"
#import "DWIconCache.h"
#import "DWText.h"
#import "NSStringExtensions.h"
#import "NSUserDefaultsExtensions.h"


@implementation AqRemoteFile

/* Initialization */

    - (id) init; {
        responses = [[NSMutableArray alloc] init];
        //hosts = [[NSMutableSet alloc] init];
        return [super init];
    }

    - (void) dealloc; 
    {
        //NSLog(@"AqRemoteFile: dealloc");

        [responses release];
        //[hosts release];
        
        [pathExtension release];
        //[name release];
        [host release];
        [length release];
        //[sha1 release];

        [nameAsTableString release];
        [nData release];
        
        [hostAsTableString release];
        [ratingAsNumber release];
        [speedAsByteSize release];
        [bitrateAsByteSize release];
        [lengthAsImage release];
        
        [artist release];
        [artistlc release];
        
        [album release];
        [albumlc release];
        
        [super dealloc];
    }
    
    - (id) copyWithZone: (id) theZone; {
        return [self retain];
    }

    
#pragma mark -
/* Adding Response */
    
    - (void) addResponse: (AqQueryResponse*) theResponse; 
    {
        id responseHost = theResponse->host;
        
        #if 0
        if ([hosts containsObject: responseHost]) {
            /* we already have a response from this host */
            return;
        } else {
            [hosts addObject: responseHost];
        }
        #endif
        
        if (!hAddress[0]) {
            id frags = [responseHost componentsSeparatedByString: @"."];
            if ([frags count] == 4) {
                hAddress[0] = [[frags objectAtIndex: 0] intValue];
                hAddress[1] = [[frags objectAtIndex: 1] intValue];
                hAddress[2] = [[frags objectAtIndex: 2] intValue];
                hAddress[3] = [[frags objectAtIndex: 3] intValue];
            }
        }

        [responses addObject: theResponse];
        count++;

        if (!name) {
            name = theResponse->name;
            size = theResponse->size;
            pathExtension = [[[name pathExtension] lowercaseString] retain];
            mediaType = AqMediaTypeForExtension(pathExtension);
        }
        
        if (!sha1) {
            sha1 = theResponse->sha1;
        }
        
        if (!bitrate) {
            bitrate = theResponse->bitrate;
            [bitrateAsByteSize release];
            bitrateAsByteSize = nil;
        }
        
        if (!year)   year   = theResponse->year;
        
        if (!album) {
            NSRange emptyRange = ([theResponse->album rangeOfString: @"   "]);
            if (emptyRange.location != NSNotFound) {
                album = [[theResponse->album substringToIndex: emptyRange.location] retain];
            } else {
                album = [theResponse->album retain];
            }
            //albumlc = [[album lowercaseString] retain];
            albumlc = [[[album substringToIndex: MIN((unsigned)10,[album length])] lowercaseString] retain];
        }

        if (!artist && theResponse->artist) {
            NSRange emptyRange = ([theResponse->artist rangeOfString: @"   "]);
            if (emptyRange.location != NSNotFound) {
                artist = [[theResponse->artist substringToIndex: emptyRange.location] retain];
            } else {
                artist = [theResponse->artist retain];
            }
            //artistlc = [[artist lowercaseString] retain];
            artistlc = [[[artist substringToIndex: MIN((unsigned)10,[artist length])] lowercaseString] retain];
        }
        
        if (!title && theResponse->title) {
            title = theResponse->title;
            [nameAsTableString release];
            nameAsTableString = nil;
            [nData release];
            nData = nil;
        }
        
        if (count == 1) {
            host = [responseHost retain];
            [hostAsTableString release];
            hostAsTableString = nil;
        } else {
            [host release];
            host = [[NSString alloc] initWithFormat: @"%i hosts", count];
            [hostAsTableString release];
            hostAsTableString = nil;
        }
        
        if (theResponse->rating > rating) {
            rating = theResponse->rating;
            ratingAsNumber = nil;
        }
        
        if (theResponse->speed > speed) {
            speed = theResponse->speed;
            speedAsByteSize = nil;
        }
    }

    - (unsigned) count; {
        return count;
    }

    - (id) responses; {
        return responses;
    }
    
    - (NSArray*) browseableHosts; {
        NSMutableArray* results = [[[NSMutableArray alloc] init] autorelease];
        unsigned i;
        for (i=0; i<[responses count]; i++) {
            AqQueryResponse* response = [responses objectAtIndex: i];
            if (response->canBrowseHost) {
                [results addObject: [NSString stringWithFormat: @"%@:%i", response->host, response->port]];
            }
        }
        return results;
    } 


#pragma mark -
/* Values */

    - (id) pathExtension; {
        return pathExtension;
    }

    - (AqMediaType) mediaType; {
        return mediaType;
    }

    - (id) icon; {
        if (!icon) icon = [[DWIconCache instance16] iconForFilePath: name];
        return icon;
    }

    - (id) name; {
        return name;
    }
    
    - (id) nameAsData; {
        if (!nData)
            nData = [[[(title) ? title : name lowercaseString] dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: YES] retain];
        return nData;
    }

    - (id) nameAsTableString; {
        if ([defaults boolForKey:@"kAqID3SongTitle"]) {
            if (!nameAsTableString) {
                nameAsTableString = [[DWTableString alloc] initWithString: (title) ? title : name attributes: [DWText smallTextAttributes]];
                [nameAsTableString setStyle: DWCollapseCenter];
            }
        } else {
            if (!nameAsTableString) {
                nameAsTableString = [[DWTableString alloc] initWithString: name attributes: [DWText smallTextAttributes]];
                [nameAsTableString setStyle: DWCollapseCenter];
            }
        }
        return nameAsTableString;
    }

    - (id) albumAsTableString; {
        if (!albumAsTableString) {
            albumAsTableString = [[DWTableString alloc] initWithString: album attributes: [DWText smallTextAttributes]];
            [albumAsTableString setStyle: DWCollapseCenter];
        }
        return albumAsTableString;
    }

    - (id) host; {
        return host;
    }
    
    - (id) hostAsTableString; {
        if (!hostAsTableString) {
            if (count > 1) hostAsTableString = DWTableStringCreateCached(host, [DWText smallBoldTextAttributes]);
            else           hostAsTableString = DWTableStringCreateCached(host, [DWText verySmallTextAttributes]);
        }
        return hostAsTableString;
    }

    - (float) rating; {
        return rating;
    }

    - (id) ratingAsNumber; {
        if (!ratingAsNumber)
            ratingAsNumber = [[NSNumber alloc] initWithFloat: rating];
        return ratingAsNumber;
    }
    
    - (int) speed; {
        return speed;
    }
    
    - (id) speedAsByteSize; {
        if (!speedAsByteSize)
            speedAsByteSize = [[DWByteSize alloc] initWithValue: speed];
        return speedAsByteSize;
    }
    
    - (int) size; {
        return size;
    }
    
    - (id) sizeAsByteSize; {
        if (!sizeAsByteSize)
            sizeAsByteSize = [[DWByteSize alloc] initWithValue: size];
        return sizeAsByteSize;
    }

    - (id) sizeTS; {
        return [[self sizeAsByteSize] tableString];
    }

    - (int) bitrate; {
        return bitrate;
    }

    - (id) bitrateAsByteSize; {
        if (!bitrateAsByteSize) {
            bitrateAsByteSize = [[DWByteSize alloc] initWithValue: bitrate];
            [bitrateAsByteSize setZeroValue: nil];
            [bitrateAsByteSize setMinimumMagnitude: 0];
            [bitrateAsByteSize setPostfix: @" kbps"];
        }
        return bitrateAsByteSize;
    }

    - (id) length; {
        return length;
    }
    
    - (id) lengthAsImage; {
        if (!lengthAsImage)
            lengthAsImage = [[length imageWithAttributes: [DWText smallTextAttributes]] retain];
        return lengthAsImage;
    }

    - (id) sha1; {
        return sha1;
    }
    

#pragma mark -
/* Download */

    - (void) download; 
    {
        /* download */

            id o, e = [responses objectEnumerator];
            id command = [[[NSMutableString alloc] initWithString: @"download"] autorelease];
            
            while ((o = [e nextObject])) {
                AqQueryResponse* qr = o;
                [command appendString: [NSString stringWithFormat: @"|%i", qr->localIndex]];
            }
        
            [command appendString: @"\n"];
            [AqCoreController writeString: command];

        /* set icon */

            static id download = nil;
            if (!download) {
                download = [[DWCachedImage alloc] initWithImage: [NSImage imageNamed: @"AcqFileDownload"]];
                [download setUsesWhiteSilhouetteWhenAppropriate: NO];
            }
            
            icon = download;
    }


#pragma mark -
/* Description */

    - (NSString*) description; {
        return [NSString stringWithFormat: @"<AqRemoteFile(%i): %@, SHA1: %@, SIZE: %i>", count, name, sha1, size];
    }

@end