/* 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.
 */
#import "tChapters.h"
#import "Movies.h"
#include "tPlayback.h"
#import "defaults.h"

@interface NSObject (tcOthers)

- (BOOL) settingForKey:(NSString *)key;
- (long) getSampleTimeValue;
- (void)savePrefs;

@end

@implementation tChapters

NSString *cleanWSpace(NSString *inputString);
double getScaleTotal(id string);
int StringToNSeconds(id string);
BOOL IsNum(char ch);

id tChapNibInstance = nil;
BOOL isAsleep = YES;

+ (id)go
{
    if (isAsleep) {
        NSWindowController *winCon = [[NSWindowController alloc] initWithWindowNibName:@"Chapters"];
        [winCon showWindow:self];
    } else {
        [tChapNibInstance open:self];
    }
    return tChapNibInstance;
}

- (void)populateMenu:(NSMenu *)aMenu
{
    NSArray *titles = [NSArray arrayWithObjects:@"Open Chapters Window", @"Get Current Time Point", @"Add New Chapter", @"Remove Chapter", @"Save As Text...", @"Open Chapters Text File...", @"Get Times From DVD...", nil];
    void *actions[] = { @selector(open:), @selector(getTimePoint2:), @selector(newChapter2), @selector(remove2:), @selector(saveChaptersToFile:), @selector(openChaptersFromFile:), @selector(openDVD:) };
    int i, n = [titles count];
    for (i=0;i<n;i++) {
        [[aMenu addItemWithTitle:[titles objectAtIndex:i] action:actions[i] keyEquivalent:@""] setTarget:self];
    }
}

- (void)setPrefSource:(id)source
{
    tinit = source;
}

- (void)controlTextDidChange:(NSNotification *)aNotification
{
    [searchButton setAction:@selector(webSearch:)];
    [searchButton setTitle:@"Search"];
}

- (void)chaptersDidChange:(id)chapters
{
    if (!shouldChange) return;
    if ([currentMovie chapters] != chapters) return;
    if ([[movieView window] isVisible] && [movieView isControllerVisible])
        [self saveChaptersToMovie:nil];
    else
        [currentMovie setChaptersNeedUpdating];
    //[chapterTable reloadData];
    [chapterTable2 reloadData];
    [controller savePrefs];
    [player setChapterTicks];
}

- (BOOL)windowShouldClose:(id)sender
{
    [bb cancel];
    //[chapWindow saveFrameUsingName:@"chapWindow"];
    //[extrasDrawer close:self];
    return YES;
}
/*
- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
    //[controller savePrefs];
    //[chapterTable selectRow:[chapterTable selectedRow] byExtendingSelection:NO];
    //lastSelection = [chapterTable selectedRow];
}
*/
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return 0;
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    NSBeep();
    return @"error";
}

- (BOOL) shouldEditIdentifier:(NSString *)idString
{
    if ([idString isEqualToString:@"Start"] && ![tinit settingForKey:@"editChapTimes"]) return NO;
    //didEdit = YES;
    if(![warn state] || [currentMovie isFileWritable]) return YES;
    int choice = NSRunAlertPanel(@"Warning", @"This file is not writable.  To save your changes you must \"Save As\".  Do you wish to edit it anyway?", @"OK", @"Cancel", @"OK And Disable Warning");
    switch (choice) {
        case NSAlertDefaultReturn:
            return YES;
        case NSAlertOtherReturn:
            [warn setState:NO];
            return YES;
        case NSAlertAlternateReturn:
            //didEdit = NO;
            return NO;
    }
    return YES;
}

- (BOOL) tableView: (NSTableView *) tableView shouldEditTableColumn: (NSTableColumn *) tableColumn row: (int) rowIndex
{
    if (currentMovie == nil) return NO;
    if ([tInit boolForKey:@"doubleClick"] && [[NSApp currentEvent] type] == NSLeftMouseDown) return NO;
    BOOL r = [self shouldEditIdentifier:[tableColumn identifier]];
	return r;
}


- (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTableView
{
    return YES;
}

- (void)tableViewColumnDidMove:(NSNotification *)aNotification
{       [self saveColumns];        }
- (void)tableViewColumnDidResize:(NSNotification *)aNotification
{       [self saveColumns];        }


- (void)doSingleClick:(id)sender
{
    if (![tInit boolForKey:@"doubleClick"]) return;
    NSTableColumn	*theColumn = nil;
    if (lastClickedColumn >= 0)
            theColumn = [[chapterTable2 tableColumns] objectAtIndex:lastClickedColumn];
    int currentSelectedRow = [chapterTable2 selectedRow];
    if (currentSelectedRow != -1 && currentSelectedRow == lastSelection ) {
        shouldEditVariable = 1;
        if( theColumn && [self shouldEditIdentifier:[theColumn identifier]] == YES ) {
            [chapterTable2 editColumn:lastClickedColumn row:currentSelectedRow withEvent:nil select:YES];
            shouldEditVariable = 0;
        }
		//else return;
		//shouldEditVariable = 0;
    } else {
        lastSelection = currentSelectedRow;
    }
}

- (IBAction)doSingleClickWithDelay:(id)sender 
{	
    if (![tInit boolForKey:@"doubleClick"]) return;
    [self performSelector:@selector(doSingleClick:) withObject:sender afterDelay:GetDblTime() / 60.0]; //Carbon Call
    lastClickedColumn = [chapterTable2 clickedColumn];
}

- (IBAction)goThereNow:(id)sender
{
    int selectedRow = [chapterTable2 selectedRow];
    if (selectedRow >= 0) {
        [player movieDidChangeTo:currentMovie];
        [currentMovie setCurrentTimeIndexSeconds:[[currentMovie chapters] timeForChapterAtIndex:selectedRow]];
    }
}

- (IBAction)doDoubleClick:(id)sender
{
    if ([tInit boolForKey:@"doubleClick"]) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doSingleClick:) object:sender];
        lastSelection = [chapterTable2 selectedRow];
        if ([chapterTable2 clickedRow] >= 0)
            [self goThereNow:nil];
    } else {
		NSTableColumn *c = [[chapterTable2 tableColumns] objectAtIndex:[chapterTable2 clickedColumn]];
		NSString * ident = [c identifier];
		if ([self shouldEditIdentifier:ident])
			[chapterTable2 editColumn:[chapterTable2 clickedColumn] row:[chapterTable2 clickedRow] withEvent:[NSApp currentEvent] select:YES];
	}
}


- (void)awakeFromNib
{
    tChapNibInstance = self;
    isAsleep = NO;
    shouldChange = YES;
	
	dvdChapsFound = nil;
    
    lastSelection = -1;
    shouldEditVariable = lastClickedColumn = 0;
    
    [chapterTable2 setTarget:self];
    [chapterTable2 setAction:@selector(doSingleClickWithDelay:)];
    [chapterTable2 setDoubleAction:@selector(doDoubleClick:)];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"dummy" ofType:@"txt"];
    dummyMovie = [[MHMovie alloc] initWithPath:path];
    [MHChapters addChaptersChangeListener:self];
    bb = nil; // [[MHBB alloc] init];
	
	// Making sure the internet lookup object has a reference to the chapter interface object (that's us!!!)
	[bb setChapterInterfaceController:self];
    [chapterTable2 registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
	[bb setTextField:resultsField];
    [bb setTextFieldForImage:picField];
    [bySoundTrack setState:[[NSUserDefaults standardUserDefaults] boolForKey:@"chapByTrack"]];
    [self byTracks:nil];
}

- (void)movieDidChangeTo:(MHMovie *)aMovie
{
    [chapterTable2 selectRow:0 byExtendingSelection:NO];
    currentMovie = aMovie;
    if (nil == aMovie)
        currentMovie = dummyMovie;
    else if (![[aMovie stringValue] isEqualToString:@"dummy"])
        [searchField setStringValue:[aMovie stringValue]];
    [self controlTextDidChange:nil];
    MHChapters *newChapters = [currentMovie chapters];
    if (nil ==  newChapters) {
        newChapters = [[MHChapters alloc] initFromMovie:aMovie];
        [aMovie setChapters:newChapters];
    }
    [chapterTable2 setDataSource:newChapters];
    [chapterTable2 reloadData];
    [bySoundTrack setState:[[currentMovie chapters] multilingual]];
    [self byTracks:self];
}


- (IBAction)add2:(id)sender
{
    [self newChapter2];
    [self getTimePoint2:nil];
    int index = [chapterTable2 selectedRow];
    int i = -1;
    NSArray *cols = [chapterTable2 tableColumns];
    while (++i<[cols count] && [[[cols objectAtIndex:i] identifier] isEqualToString:@"Start"]);
    if (i<[cols count])
        [chapterTable2 editColumn:i row:index withEvent:nil select:YES];
	[self chaptersDidChange:[currentMovie chapters]];
}

- (void)newChapter2
{
    if (nil == currentMovie) return;
    int index = [chapterTable2 selectedRow];
    index++;
    id chap = [currentMovie chapters];
    [chap addChapterAtIndex:index];
    //[chapterTable reloadData];
    [chapterTable2 reloadData];
    [chapterTable2 selectRow:index byExtendingSelection:NO];
    [chapterTable2 selectRow:index byExtendingSelection:NO];
    [chapterTable2 scrollRowToVisible:index];
}

- (IBAction)remove2:(id)sender
{
    if (nil == currentMovie) return;
    shouldChange = NO;
    BOOL changed = NO;
    int i;
    for (i=[chapterTable2 numberOfRows]-1;i>=0;i--) {
        if ([chapterTable2 isRowSelected:i]) {
            [[currentMovie chapters] removeChapterAtIndex:i];
            changed = YES;
        }
    }
    shouldChange = YES;
    if (changed)
        [self chaptersDidChange:[currentMovie chapters]];
    //[chapterTable reloadData];
    [chapterTable2 reloadData];
    [chapterTable2 deselectAll:self];
    //[self change];
}

- (IBAction)getTimePoint2:(id)sender
{
    if (nil == currentMovie) return;
    int index = [chapterTable2 selectedRow];
    
    if (index < 0) {
        [self add2:nil];
    } else {
        double time = [player getTimeValue];
        [[currentMovie chapters] setSeconds:time forIndex:index];
        [chapterTable2 reloadData];
    }
    //[self change];
}

- (IBAction)autoNumber:(id)sender
{
    //NSTableColumn *col = [[NSTableColumn alloc] initWithIdentifier:@"Content"];
    NSArray *cols = [chapterTable2 tableColumns];
    MHChapters *chaps = [currentMovie chapters];
    if (!chaps) return;
    shouldChange = NO;
    int i, j, k, m = [cols count], n = [chapterTable2 numberOfRows];
    NSString *title, *idString;
    NSTableColumn *col;
    char ch;
    for (i=0;i<n;i++) {
        for (j=0;j<m;j++) {
            col = [cols objectAtIndex:j];
            idString = [col identifier];
            if (idString && ![idString isEqualToString:@"Start"]) {
                title = [chaps tableView:nil objectValueForTableColumn:col row:i];
                k = 0;
                while (YES) {
                    ch = [title characterAtIndex:k];
                    if ((ch < '0' || ch > '9') && ch != '.' && ch != ' ') break;
                    k++;
                }
                title = [NSString stringWithFormat:@"%d. %@", i+1, [title substringFromIndex:k]];
                [chaps tableView:nil setObjectValue:title forTableColumn:col row:i];
            }
        }
    }
    shouldChange = YES;
    [self chaptersDidChange:chaps];
    [chapterTable2 reloadData];
}

- (IBAction)deNumber:(id)sender
{
    MHChapters *chaps = [currentMovie chapters];
    NSArray *cols = [chapterTable2 tableColumns];
    if (!chaps) return;
    shouldChange = NO;
    int i, j, k, m = [cols count], n = [chapterTable2 numberOfRows];
    NSString *title, *idString;
    NSTableColumn *col;
    char ch;
    for (i=0;i<n;i++) {
        for (j=0;j<m;j++) {
            col = [cols objectAtIndex:j];
            idString = [col identifier];
            if (idString && ![idString isEqualToString:@"Start"]) {
                title = [chaps tableView:nil objectValueForTableColumn:col row:i];
                k = 0;
                while (YES) {
                    ch = [title characterAtIndex:k];
                    if ((ch < '0' || ch > '9') && ch != '.' && ch != ' ') break;
                    k++;
                }
                [chaps tableView:nil setObjectValue:[title substringFromIndex:k] forTableColumn:col row:i];
            }
        }
    }
    shouldChange = YES;
    [self chaptersDidChange:chaps];
    [chapterTable2 reloadData];
}

- (IBAction)more:(id)sender
{
    /*
    if ([extrasDrawer state] != NSDrawerClosedState) // don't ask me why but this is right
        [moreButton setTitle:@"More"];
    else
        [moreButton setTitle:@"Less"];
    [extrasDrawer toggle:self];
    */
}

- (IBAction)webSearch:(id)sender
{	
	// Delegate the search to MHBB (MHBB?)
	[bb search:[searchField stringValue]];
	
    //[searchButton setAction:@selector(webSearchAgain:)];
    //[searchButton setTitle:@"Try Again"];
}

- (IBAction)webSearchAgain:(id)sender
{
    [bb bbSearchAgain:self];
}

- (void)webSearchComplete
{

	// Copy the results to a local variable (in case the bb object disappears)
	NSArray			* results = [[bb bbResults] copyWithZone:NULL];

	// If there is more than 1 result
	// Populate the pop up window and show it
	if ([results count] > 1)
	{
		NSEnumerator	* movieEnumerator = [results objectEnumerator];
		NSDictionary	* theMovie;
		NSString		* theMovieTitle;
		int i = 0;

		// Empty the Pop Up window
		[searchResultsPopUp removeAllItems];
		
		while (theMovie = [movieEnumerator nextObject])
		{
			// Prepare the string with the name of the movie and add it to the pop up window
			theMovieTitle = [[NSString alloc] initWithFormat:@"%i. %@", i+1, [theMovie objectForKey:@"title"]];
			[searchResultsPopUp addItemWithTitle:theMovieTitle];
			[theMovieTitle release];
			i++;
		}

		// Show the pop up window
		[searchResultsPopUp setHidden:false];
	}
	else
	{
		[searchResultsPopUp setHidden:true];
	}
	
	if([results count] != 0)				
	{
		Boolean			hasChapters;
	
		// Get the DVD chapters of the first movie in the results
		hasChapters = [bb getDVDFeatures:[[results objectAtIndex:0] objectForKey:@"link"]];
		
		// If the chapters exist, display them
		if(hasChapters)
		{
			[bb displayResultsForTitle:[[results objectAtIndex:0] objectForKey:@"title"]];
		}
		else
		{
			[resultsField setStringValue:@"(No Chapters for this DVD)"];
		}
	}
	else
	{
		// If there are no results, let the user know
		[resultsField setStringValue:@"(No Results)"];
	}

}

- (void)displayChaptersForMovie2:(id)moviePopUp
{

	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	int	i;
	
	i = [moviePopUp indexOfSelectedItem];
		
	if(i > -1 && i < 10)
	{
		// Copy the results to a local variable
		Boolean			hasChapters = FALSE;
		NSArray			* results = [[bb bbResults] copyWithZone:NULL];
		
		[resultsField performSelectorOnMainThread:@selector(setStringValue:) withObject:@"..." waitUntilDone:YES];
		// Get the DVD chapters of the movie selected in the Pop Up button
		hasChapters = [bb getDVDFeatures:[[results objectAtIndex:i] objectForKey:@"link"]];
		
		// If the chapters exist, display them
		if(hasChapters == TRUE)
		{
			[bb displayResultsForTitle:[[results objectAtIndex:i] objectForKey:@"title"]];
		}
		else
		{
			// No idea why the first call doesn't work, but the second one does
			//[resultsField setStringValue:@"(No Chapters for this DVD)"];
			[resultsField performSelectorOnMainThread:@selector(setStringValue:) withObject:[NSString stringWithFormat:@"(No Chapters for this DVD)"] waitUntilDone:NO];
		}
	}
	[pool release];
	
}
- (IBAction)displayChaptersForMovie:(id)moviePopUp
{
	[NSThread detachNewThreadSelector:@selector(displayChaptersForMovie2:) toTarget:self withObject:moviePopUp];
}

- (IBAction)choose:(id)sender
{
    NSMovie *movie = nil;
    if ([tinit settingForKey:@"chapScale"])
        movie = currentMovie;
    MHChapters *ch = [bb chaptersScaledToMovie:movie];
	
	
	
    [[currentMovie chapters] updateWithArray:[ch array]];
}

- (void)saveColumns
{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSArray *cols = [chapterTable2 tableColumns];
    NSMutableDictionary *saved = [defs objectForKey:@"chapter table columns"]; // not mutable yet!
    if (!saved) saved = [NSMutableDictionary dictionary];
    else saved = [NSMutableDictionary dictionaryWithDictionary:saved];
    int i, n = [cols count];
    for (i=0;i<n;i++) {
        NSTableColumn *col = [cols objectAtIndex:i];
        NSString *name = [col identifier];
        if (name) [saved setObject:[NSNumber numberWithInt:[col width]] forKey:name];
    }
    [defs setObject:saved forKey:@"chapter table columns"];
    [defs synchronize];
}

- (void)restoreColumns
{
    NSDictionary *saved = [[NSUserDefaults standardUserDefaults] objectForKey:@"chapter table columns"];
    NSArray *cols = [chapterTable2 tableColumns];
    int i, n = [cols count];
    for (i=0;i<n;i++) {
        NSTableColumn *col = [cols objectAtIndex:i];
        NSString *name = [col identifier];
        if (name) {
            NSNumber *width = [saved objectForKey:name];
            if (width) [col setWidth:[width intValue]];
        }
    }
}

- (IBAction)byTracks:(id)sender
{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    BOOL isOn = [bySoundTrack state];
    [defs setBool:isOn forKey:@"chapByTrack"];
    NSArray *langs = [currentMovie languages];
    int i;
    if (isOn) {
        [chapterTable2 removeAllColumns];
        [chapterTable2 addColumnWithName:@"Start"];
        for (i=0;i<[langs count];i++)
            [chapterTable2 addColumnWithName:[NSString stringWithFormat:@"%@ Content", [langs objectAtIndex:i]]];
    } else {
        NSArray *cols = [chapterTable2 tableColumns];
        for (i=[cols count]-1;i >= 0; i--) {
            NSTableColumn *col = [cols objectAtIndex:i];
            if (![[col identifier] isEqualToString:@"Start"])
                [chapterTable2 removeTableColumn:col];
        }
        [chapterTable2 addColumnWithName:@"Content"];
    }
    [[currentMovie chapters] setMultilingual:isOn languages:langs];
    [self restoreColumns];
    [chapterTable2 reloadData];
    if ([movieView isControllerVisible]) {
        [movieView showController:NO adjustingSize:NO];
        [movieView showController:YES adjustingSize:NO];
    }
}

- (IBAction)copyMenu:(id)sender
{
    if (![sender isKindOfClass:[NSEvent class]]) return;
    NSMenu *menu = [[[NSMenu alloc] init] autorelease];
    id model = [theTable dataSource];
    int i, n = [theTable numberOfRows];
    for (i=0;i<n;i++) {
        NSMenuItem *item = [[[NSMenuItem alloc] init] autorelease];
        [item setTitle:[[model movieForIndex:i] stringValue]];
        [item setTarget:self];
        if ([model movieForIndex:i] != currentMovie)
            [item setAction:@selector(copyFrom:)];
        [menu addItem:item];
    }
    [NSMenu popUpContextMenu:menu withEvent:sender forView:nil];
}

- (IBAction)copyFrom:(id)sender
{
    int index = [[sender menu] indexOfItem:sender];
    NSArray *newChaps = [[[[theTable dataSource] movieForIndex:index] chapters] array];
    [[currentMovie chapters] empty];
    [[currentMovie chapters] addObjectsFromArray:newChaps];
    [chapterTable2 reloadData];
}

- (IBAction)saveChaptersToMovie:(id)sender
{
    //NSLog(@"tChapters saveChaptersToMovie");
    if (nil == currentMovie) return;
    float rate = [movieView rate];
    [[currentMovie chapters] addToMovie:currentMovie];
    [currentMovie setEdited:YES];
    [movieView setMovie:nil];
    [movieView setMovie:currentMovie];
    [movieView setRate:rate];
}

- (IBAction)saveChaptersToFile:(id)sender
{
    //NSLog(@"tChapters saveChaptersToFile");
    if (nil == currentMovie) return;
    NSSavePanel *sp = [NSSavePanel savePanel];
    int runResult;
    NSString *name = [currentMovie stringValue];
    if ([name isEqualToString:@"dummy"])
        name = [searchField stringValue];
    if (![name length])
        name = @"Chapters.txt";
    else
        name = [NSString stringWithFormat:@"Chapters of %@.txt", name];
    
    runResult = [sp runModalForDirectory:nil file:name];

    if (runResult == NSOKButton)
        [[currentMovie chapters] saveToFile:[sp filename]];
}

- (IBAction)openChaptersFromFile:(id)sender
{
    if (nil == currentMovie) return;
    NSArray *selection = [MHUtil showOpenPanel];
    if (![selection count]) return;
    [[currentMovie chapters] empty];
    NSMovie *scaleTo = nil;
    if ([tinit settingForKey:@"scaleImportedChapters"])
        scaleTo = currentMovie;
    NSURL *url = [selection objectAtIndex:0];
    NSString *suf = [[[url path] substringFromIndex:[[url path] length]-4] lowercaseString];
    if ([suf isEqualToString:@".mov"]) [[currentMovie chapters] parseMovFile:url scaleToMovie:scaleTo];
    else if ([suf isEqualToString:@".ogm"]) [[currentMovie chapters] parseOgmFile:url scaleToMovie:scaleTo];
    else if ([suf isEqualToString:@".mkv"]) [[currentMovie chapters] parseMkvFile:url scaleToMovie:scaleTo];
    else if ([suf isEqualToString:@".txt"]) [[currentMovie chapters] parseTextFile:url scaleToMovie:scaleTo];
    [bySoundTrack setState:[[currentMovie chapters] multilingual]];
    [self byTracks:self];
    //[chapterTable reloadData];
    [chapterTable2 reloadData];
}

- (IBAction)revert:(id)sender
{
    if (nil == currentMovie) return;
    [[currentMovie chapters] getChaptersFromMovie:currentMovie];
    //[chapterTable reloadData];
    [chapterTable2 reloadData];
    //[self unChange];
}


- (IBAction)removeChapters:(id)sender
{
    if (nil == currentMovie) return;
    
    int result = NSRunAlertPanel(@"Delete Chapters",[NSString stringWithFormat:@"Delete chapters from the movie \"%@\"?", [currentMovie stringValue]],@"Yes, Delete",@"No, Never Mind",nil);
    if (result == NSAlertAlternateReturn) return;
    
    [[currentMovie chapters] removeChaptersFromMovie:currentMovie];
    [[currentMovie chapters] empty];
    [currentMovie setEdited:YES];
    [(NSMovieView *)movieView setMovie:nil];
    [movieView setMovie:currentMovie];
    //[self change];
}

- (BOOL) setChapters:(MHChapters *)newChapters
{
    if (nil == newChapters) return NO;
    if (nil == currentMovie) return NO;
	if ([newChapters isKindOfClass:[MHChapters class]]) {
		newChapters = [newChapters array];
	}
	[[currentMovie chapters] updateWithArray:newChapters];
    //[currentMovie setChapters:newChapters];
    //[[currentMovie chapters] addToMovie:currentMovie];
    //[chapterTable setDataSource:newChapters];
    //[chapterTable2 setDataSource:newChapters];
    //[chapterTable reloadData];
    [chapterTable2 reloadData];
    //[self unChange];
    return YES;
}

- (IBAction)openDVD:(id)sender
{
    if (nil == currentMovie) {
        NSLog(@"tChapters: no dummy movie to work with");
        return;
    }
    NSString *path = [self getDVDPath];
    
    if (!path) {
        NSArray *theSelection = [MHUtil showOpenPanel];
        if ([theSelection count] == 0) return;
    
        path = [[theSelection objectAtIndex:0] path];
    }
    
    [dvdPopup removeAllItems];
    [dvdPopup addItemsWithTitles:[MHChapters titlesOfDVD:path]];
	[dvdPopup addItemWithTitle:@"<Save all to files>"];
    [dvdWindow setTitle:path];
    [dvdWindow makeKeyAndOrderFront:nil];
    
    if (![[searchField stringValue] length]) {
        if ([path hasSuffix:@"VIDEO_TS"] || [path hasSuffix:@"VIDEO_TS/"])
            path = [path stringByDeletingLastPathComponent];
        NSMutableString *displayString = [NSMutableString stringWithString:[path lastPathComponent]];
        [displayString replaceOccurrencesOfString:@"_" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [displayString length])];
        [searchField setStringValue:displayString];
    }
    
    //[[currentMovie chapters] parseDVD:path title:[title intValue]];
    //[chapterTable reloadData];
}

- (NSString *)getDVDPath
{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *vols = [fm directoryContentsAtPath:@"/Volumes"];
    NSString *aPath, *goodPath = nil;
    BOOL isDir;
    if (!vols || ![vols count]) return nil;
    int i, n = [vols count];
    for (i=0;i<n;i++) {
        aPath = [NSString stringWithFormat:@"/Volumes/%@/VIDEO_TS", [vols objectAtIndex:i]];
        if ([fm fileExistsAtPath:aPath isDirectory:&isDir]) {
            if (goodPath) return nil;
            goodPath = aPath;
        }
    }
    return goodPath;
}

- (IBAction)openDVDreal:(id)sender
{
    if (!currentMovie) return;
    NSString *selectionTitle = [dvdPopup titleOfSelectedItem];
	int choice = 1;
	int i = 0;
	int n = 1;
	BOOL doALL = NO;
	NSString *path = nil;
	NSOpenPanel *theOpenPanel = [NSOpenPanel openPanel];
	NSArray *theSelection;
	NSScanner *scan = [NSScanner scannerWithString:selectionTitle];
	if ([selectionTitle hasPrefix:@"<Save"]) {
		doALL = YES;
		n = [dvdPopup numberOfItems]-1;
		int result;
			
		[theOpenPanel setCanChooseFiles:NO];
		[theOpenPanel setCanChooseDirectories:YES];
		[theOpenPanel setResolvesAliases:YES];
		[theOpenPanel setAllowsMultipleSelection:NO];
		[theOpenPanel setTitle:@"Choose output destination"];
		result = [theOpenPanel runModalForDirectory:nil file:nil types:nil];
		if (result == NSOKButton) {
			theSelection = [theOpenPanel URLs];
			if ([theSelection count])
				path = [[theSelection objectAtIndex:0] path];
			else
				return;
		} else {
			return;
		}
	}
	for (i=0;i<n;i++) {
		if (doALL) scan = [NSScanner scannerWithString:[dvdPopup itemTitleAtIndex:i]];
		[scan scanPastString:@"Title "];
		[scan scanInt:&choice];
		NSMovie *movie = nil;
		if ([tinit settingForKey:@"scaleDVDChapters"])
			movie = currentMovie;
		[[currentMovie chapters] parseDVD:[dvdWindow title] title:choice scaleToMovie:movie];
		if (doALL) {
			NSString *name = [NSString stringWithFormat:@"Chapters of %d.txt", choice];
			name = [path stringByAppendingPathComponent:name];
			name = [MHUtil uniquePath:name];
			[[currentMovie chapters] saveToFile:name];
		}
	}
	//[chapterTable reloadData];
	[chapterTable2 reloadData];
	[dvdWindow orderOut:nil];
	
}

- (MHMovie *)currentMovie
{
	if (currentMovie == dummyMovie) return nil;
	return currentMovie;
}

@end
