/* Copyright (c) 2004, Noah Sorscher
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 	• 	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * 	• 	Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * 	• 	Neither the name of the Noah Sorscher nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
//
//  tFileSave.m
//  Hootenanny
//
//  Created by Noah Sorscher on Sun Nov 23 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import "tFileSave.h"

@interface tFileSave (private)

- (void) saveOneMovie:(NSNotification *)aNotification;

@end

@implementation tFileSave


- (id) init
{
    self = [super init];
    [self clear];
    filesToSave = [[NSMutableArray alloc] init];
    return self;
}

- (void) clear
{
    cancelled = sameDir = NO;
    flattening = -1;
    myTask = nil;
    dirPath = tempPath = nil;
    resourcePath = [[[NSBundle mainBundle] pathForResource:@"qtFlatten" ofType:nil] retain];
}

- (void) dealloc
{
    [filesToSave release];
}

- (void) setProgressBar:(id)bar
{   progBar = bar;          }

- (void) setTextField:(id)field
{   textField = field;      }

- (void) setWindow:(id)aWindow
{   window = aWindow;       }

- (void) setSaveBeep:(id)beep
{   saveBeep = beep;        }

- (void) setStartButton:(id)button
{   startButton = button;   }

- (void) setSameDir:(BOOL)same
{   sameDir = same;         }

- (void) setDirPath:(NSString *)aPath
{   dirPath = aPath;        }

- (void) addMovie:(MHMovie *)aMovie
{
    if (aMovie)
        [filesToSave addObject:aMovie];
}

- (void) removeMovie:(MHMovie *)aMovie
{
    if (aMovie)
        [filesToSave removeObject:aMovie];
}

- (void) removeMovieAtIndex:(int)index
{
    if (index < [filesToSave count])
        [filesToSave removeObjectAtIndex:index];
}

- (void) removeAllMovies
{
    [filesToSave removeAllObjects];
}

- (void) cancel
{
    cancelled = YES;
    [myTask terminate];
    [window performClose:self];
}

// 0 = flattening, 1 = reference, 2 = save-in-place
- (void) saveFilesFlattening:(int)toFlatten
{
    cancelled = NO;
    [startButton setEnabled:NO];
    flattening = toFlatten;
    [progBar startAnimation:self];
    NSArray *comps = [dirPath componentsSeparatedByString:@"/"];
    int i, j;
    NSString *aDir;
    NSString *aTempPath, *newPath = @"/";
    BOOL isDir;
    NSFileManager *fm = [NSFileManager defaultManager];
    for (i=0;i<[comps count];i++) {
        aDir = [comps objectAtIndex:i];
        if ([aDir length]) {
            newPath = [newPath stringByAppendingPathComponent:aDir];
            if (![fm fileExistsAtPath:newPath isDirectory:&isDir]) {
                [fm createDirectoryAtPath:newPath attributes:nil];
            } else if (!isDir) {
                aTempPath = newPath;
                j = 1;
                while ([fm fileExistsAtPath:aTempPath])
                    aTempPath = [NSString stringWithFormat:@"%@ %d", newPath, j++];
                newPath = aTempPath;
                [fm createDirectoryAtPath:newPath attributes:nil];
            }
        }
    }
    dirPath = [newPath copy];
    if (toFlatten == 0)
        [self saveOneMovie:nil];
    else
        [NSThread detachNewThreadSelector:@selector(saveAllMovies) toTarget:self withObject:nil];
}

- (void) saveAllMovies
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    while ([filesToSave count] && !cancelled)
        [self saveOneMovie:nil];
    [self saveOneMovie:nil];
    [pool release];
}

- (void)saveOneMovie:(NSNotification *)aNotification
{
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
    [myTask release];
    myTask = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:tempPath])
        [[NSFileManager defaultManager] removeFileAtPath:tempPath handler:nil];
    tempPath = nil;
    if ([filesToSave count] && !cancelled) {
        MHMovie *aMovie = [filesToSave objectAtIndex:0];
        //NSLog(@"got movie to save: %d", [aMovie retainCount]);
        [filesToSave removeObjectAtIndex:0];
        //NSLog(@"removed from array: %d", [aMovie retainCount]);
        NSString *name = [aMovie stringValue];
        [textField performSelectorOnMainThread:@selector(setStringValue:) withObject:[NSString stringWithFormat:@"Saving:  %@", name] waitUntilDone:NO];
        //[[window contentView] setNeedsDisplay:YES];
        NSString *filePath = [aMovie objectForKey:@"File Name"];
        if (!filePath) filePath = name;
        if ([filePath hasPrefix:@"."])
            filePath = [NSString stringWithFormat:@" %@", filePath];
        filePath = [NSMutableString stringWithString:filePath];
        if (![filePath hasSuffix:@".mov"]) [(NSMutableString *)filePath appendString:@".mov"];
        [(NSMutableString *)filePath replaceOccurrencesOfString:@":" withString:@"-" options:NSLiteralSearch range:NSMakeRange(0, [filePath length])];
        tempPath = [MHUtil uniquePath:[[MHUtil supportDir] stringByAppendingPathComponent:filePath]];
        if (sameDir)
            dirPath = [[aMovie objectForKey:@"File Path"] stringByDeletingLastPathComponent];
        filePath = [MHUtil uniquePath:[dirPath stringByAppendingPathComponent:filePath]];
        if (flattening == 0) {
            [aMovie saveToPath:tempPath flatten:NO];
            myTask = [[NSTask alloc] init];
            [myTask setLaunchPath:resourcePath];
            [myTask setArguments:[NSArray arrayWithObjects:tempPath, filePath, nil]];
            //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveOneMovie:) name:NSTaskDidTerminateNotification object:myTask];
            [myTask launch];
            [myTask waitUntilExit];
            // Custom Icon
            NSImage *image = [aMovie image];
            if (image) {
                IconFamily *icon = [IconFamily iconFamilyWithThumbnailsOfImage:image];
                [icon setAsCustomIconForFile:filePath];
            }
            [self saveOneMovie:nil];
        } else if (flattening == 1)
            [aMovie saveToPath:filePath flatten:NO];
        else if (flattening == 2)
            [aMovie saveInPlace];
        //NSLog(@"saved: %d", [aMovie retainCount]);
    } else {
        [textField setStringValue:@""];
        [window performClose:self];
        [progBar stopAnimation:self];
        if ([saveBeep state])
            [[NSSound soundNamed:@"Glass.aiff"] play];
        [startButton setEnabled:YES];
    }
}

@end
