/*
** AqiTunesController
** 
** CHANGES:
** 0.1 (pozytron) Added code to get playlist name from defaults
*/

#import "AqiTunesController.h"
#import "NSUserDefaultsExtensions.h"


@implementation AqiTunesController

/* Main API Entry */

    + (void) _handleCompletedFile: (id) thePath;
    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        NS_DURING

        if ([defaults boolForKey: @"kAqAddSong"])
        {
            BOOL success = NO;
            
            if ([defaults boolForKey: @"kAqAddSongToPlaylist"]) {
                if ([defaults boolForKey: @"kAqPlaylistShouldLimit"]) {
                    success = [AqiTunesController addSongToPlaylist: thePath andPruneToSize: [defaults integerForKey: @"kAqPlaylistLimit"]];
                } else {
                    success = [AqiTunesController addSongToPlaylist: thePath];
                }
            } else {
                success = [AqiTunesController addSongToLibrary: thePath];
            }
            
            switch ([defaults integerForKey: @"kAqPlaySong"])
            {
                case 0:
                    break;

                case 1:
                    [AqiTunesController playSong: thePath];
                    break;

                case 2:
                    [AqiTunesController playSongIfNotPlaying: thePath];
                    break;
            }

            if (success && [defaults boolForKey: @"kAqDeleteAfterImport"]) {
                [AqiTunesController moveFileToTrash: thePath];
            }
        }

        NS_HANDLER
        
            NSLog(@"AqiTunesController: %@", localException);
        
        NS_ENDHANDLER

        [pool release];
    }

    + (void) handleCompletedFile: (id) thePath; {
        thePath = [thePath stringByExpandingTildeInPath];
        if ([[NSFileManager defaultManager] fileExistsAtPath: thePath])
            //[NSThread detachNewThreadSelector: @selector(_handleCompletedFile:) toTarget: [AqiTunesController class] withObject: thePath];
            [AqiTunesController _handleCompletedFile: thePath];
    }


/* AppleScript */

    + (void) moveFileToTrash: (id) thePath;
    {
        NSDictionary* error = nil;
    
        id source = [NSString stringWithFormat:
            @"                                                              \n\
            tell application \"Finder\"                                     \n\
                    move POSIX file \"%@\" as alias to trash                \n\
            end tell                                                        \n\
            ", thePath];
    
        id as = [[[NSAppleScript alloc] initWithSource: source] autorelease];
        [as executeAndReturnError: &error];
        
        if (error) {
            NSLog(source);
            NSLog(@"AqiTunesController: moveFileToTrash: %@", error);
        }
    }

    + (BOOL) addSongToLibrary: (id) thePath; 
    {
        NSDictionary* error = nil;
    
        id source = [NSString stringWithFormat:
            @"                                                              \n\
            tell application \"iTunes.app\"                                 \n\
                    add POSIX file \"%@\" as alias to first source          \n\
            end tell                                                        \n\
            ", thePath];
    
        id as = [[[NSAppleScript alloc] initWithSource: source] autorelease];
        [as executeAndReturnError: &error];
        
        if (error) {
            NSLog(source);
            NSLog(@"AqiTunesController: addSongToLibrary: %@", error);
            return NO;
        } else {
            return YES;
        }
    }
    
    + (BOOL) addSongToPlaylist: (id) thePath; 
    {
        NSDictionary* error = nil;
        NSString* playlistName = [defaults stringForKey: @"kAqPlaylistName"];
    
        id source = [NSString stringWithFormat:
            @"                                                                                              \n\
            tell application \"iTunes.app\"                                                                 \n\
                    copy \"%@\" to thePL                                                                    \n\
                                                                                                            \n\
                    if not (exists playlist thePL) then                                                     \n\
                            set plist to make new playlist                                                  \n\
                            set the name of plist to the thePL                                              \n\
                    else                                                                                    \n\
                            set plist to playlist thePL                                                     \n\
                    end if                                                                                  \n\
                                                                                                            \n\
                    set nfile to add POSIX file \"%@\" as alias to first source                             \n\
                    set fileExists to no                                                                    \n\
                    set pCount to (get count of every track of plist)                                       \n\
                                                                                                            \n\
                    repeat with i from 1 to pCount                                                          \n\
                            if (nfile's database ID is equal to database ID of track i of plist) then       \n\
                                    set fileExists to yes                                                   \n\
                            end if                                                                          \n\
                    end repeat                                                                              \n\
                                                                                                            \n\
                    if fileExists is equal to no then                                                       \n\
                        add POSIX file \"%@\" as alias to playlist thePL                                    \n\
                    end if                                                                                  \n\
                                                                                                            \n\
            end tell                                                                                        \n\
            ", playlistName, thePath, thePath];
    
        id as = [[[NSAppleScript alloc] initWithSource: source] autorelease];
        [as executeAndReturnError: &error];
        
        if (error) {
            NSLog(source);
            NSLog(@"AqiTunesController: addSongToPlaylist: %@", error);
            return NO;
        } else {
            return YES;
        }
    }

    + (BOOL) addSongToPlaylist: (id) thePath andPruneToSize: (int) theSize;
    {
        NSDictionary* error = nil;
        NSString* playlistName = [defaults stringForKey: @"kAqPlaylistName"];
    
        id source = [NSString stringWithFormat:
            @"                                                                                              \n\
            tell application \"iTunes.app\"                                                                 \n\
                    copy \"%@\" to thePL                                                                    \n\
                                                                                                            \n\
                    if not (exists playlist thePL) then                                                     \n\
                            set plist to make new playlist                                                  \n\
                            set the name of plist to the thePL                                              \n\
                    else                                                                                    \n\
                            set plist to playlist thePL                                                     \n\
                    end if                                                                                  \n\
                                                                                                            \n\
                    set nfile to add POSIX file \"%@\" as alias to first source                             \n\
                                                                                                            \n\
                    -- prune playlist to defined size                                                       \n\
                                                                                                            \n\
                    set pCount to (get count of every track of plist)                                       \n\
                                                                                                            \n\
                    if pCount is greater than %i then                                                       \n\
                            repeat with i from 1 to pCount - %i                                             \n\
                                    delete track 1 of plist                                                 \n\
                            end repeat                                                                      \n\
                    end if                                                                                  \n\
                                                                                                            \n\
                    -- check if the file already exists                                                     \n\
                                                                                                            \n\
                    set fileExists to no                                                                    \n\
                    set pCount to (get count of every track of plist)                                       \n\
                                                                                                            \n\
                    repeat with i from 1 to pCount                                                          \n\
                            if (nfile's database ID is equal to database ID of track i of plist) then       \n\
                                    set fileExists to yes                                                   \n\
                            end if                                                                          \n\
                    end repeat                                                                              \n\
                                                                                                            \n\
                    if fileExists is equal to no then                                                       \n\
                        add POSIX file \"%@\" as alias to playlist thePL                                    \n\
                    end if                                                                                  \n\
                                                                                                            \n\
            end tell                                                                                        \n\
            ", playlistName, thePath, theSize+1, theSize+1, thePath];
    
        id as = [[[NSAppleScript alloc] initWithSource: source] autorelease];
        [as executeAndReturnError: &error];
        
        if (error) {
            NSLog(source);
            NSLog(@"AqiTunesController: addSongToPlaylist: %@", error);
            return NO;
        } else {
            return YES;
        }
    }
    
    + (void) playSong: (id) thePath;
    {
        NSDictionary* error = nil;
    
        id source = [NSString stringWithFormat:
            @"                                                  \n\
            tell application \"iTunes.app\"                     \n\
                    play POSIX file \"%@\" as alias             \n\
            end tell                                            \n\
            ", thePath];
    
        id as = [[[NSAppleScript alloc] initWithSource: source] autorelease];
        [as executeAndReturnError: &error];
        
        if (error) {
            NSLog(source);
            NSLog(@"AqiTunesController: playSong: %@", error);
        }
    }
    
    + (void) playSongIfNotPlaying: (id) thePath;
    {
        NSDictionary* error = nil;
    
        id source = [NSString stringWithFormat:
            @"                                                  \n\
            tell application \"iTunes.app\"                     \n\
                    if player state is not playing then         \n\
                            play POSIX file \"%@\" as alias     \n\
                    end if                                      \n\
            end tell                                            \n\
            ", thePath];
    
        id as = [[[NSAppleScript alloc] initWithSource: source] autorelease];
        [as executeAndReturnError: &error];
        
        if (error) {
            NSLog(source);
            NSLog(@"AqiTunesController: playSongIfNotPlaying: %@", error);
        }
    }

@end