#import "MyController.h"

#define DragDropAudioPboardType @"MyAudioPboardType"	

@implementation MyController

-(void)awakeFromNib
{
    // The "tableRecordsArray" array holds paths to MP3s in the table
    tableRecordsArray=[[NSMutableArray alloc] init];
	songsFullPath=[[NSMutableArray alloc] init];
    DelegateController=[[MyController alloc] init];
	[songTable setDelegate:DelegateController];

    [songTable setDoubleAction:@selector(playSong:)];
	
	 [songTable registerForDraggedTypes:[NSArray arrayWithObjects:DragDropAudioPboardType,NSFilenamesPboardType,nil]];

	isRunning=NO;
    
    [[NSNotificationCenter defaultCenter] addObserver: songTable selector: @selector(stopPlaying:) name: NSApplicationWillTerminateNotification object:NSApp];
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [tableRecordsArray count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)row
{
	id theRecord, theValue;
    
    theRecord = [tableRecordsArray objectAtIndex:row];
    theValue = [theRecord objectForKey:[aTableColumn identifier]];
    
    return theValue;
	
}

- (BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(int)row
{    
	return NO; 
}

- (BOOL)isFileUTIMP3:(NSString *)filePath 
{	
    BOOL isMP3File = NO;
    FSRef fileRef;
    Boolean isDirectory;
	
    if (FSPathMakeRef((const UInt8 *)[filePath fileSystemRepresentation], &fileRef, &isDirectory) == noErr)
    {
        // get the content type (UTI) of this file
        CFDictionaryRef values = NULL;
        CFStringRef attrs[1] = { kLSItemContentType };
        CFArrayRef attrNames = CFArrayCreate(NULL, (const void **)attrs, 1, NULL);
		
        if (LSCopyItemAttributes(&fileRef, kLSRolesViewer, attrNames, &values) == noErr)
        {
            if (values != NULL)
            {
                CFTypeRef uti = CFDictionaryGetValue(values, kLSItemContentType);
                if (uti != NULL)
                {
					if (UTTypeConformsTo(uti, kUTTypeMP3)) 
					{
						isMP3File = YES;
					}
					else 
					{
						 if(UTTypeConformsTo(uti, CFSTR("public.aifc-audio")))  //.aiff files is ok
							
							// isAIFFFile = YES;
							 isMP3File = YES;
					}
				
                CFRelease(values);
            }
        }
		
        CFRelease(attrNames);
    }
}
    return isMP3File;
}

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op
{
	int i;
	NSArray *filesList;
	NSArray *typeArray=[NSArray arrayWithObjects:DragDropAudioPboardType,NSFilenamesPboardType,nil];
    NSString *filePath,*availableType,*lastPathOfFileName;
	BOOL foundMP3 = NO;
	NSPasteboard *pasteboard = [info draggingPasteboard];
	if ([[pasteboard types] containsObject:NSFilenamesPboardType]) {

		availableType=[pasteboard availableTypeFromArray:typeArray];
		filesList=[pasteboard propertyListForType:availableType];
		for (i=0;i<[filesList count];i++)
		{
			filePath=[filesList objectAtIndex:i];
			lastPathOfFileName=[filePath lastPathComponent];
			NSLog(@"file path is %@",filePath);
			if ([self isFileUTIMP3:filePath]) {
				// Got an MP3 file, set appropriate NSDragOperation		
				FSRef ref;
				Boolean isDirectory;
				if (FSPathMakeRef((const UInt8 *)[filePath fileSystemRepresentation], &ref, &isDirectory) == noErr)
				{
					FSCatalogInfo catInfo;
					if (FSGetCatalogInfo(&ref, (kFSCatInfoContentMod | kFSCatInfoDataSizes), &catInfo, nil, nil, nil) == noErr)
					{
						CFAbsoluteTime cfTime;
						if (UCConvertUTCDateTimeToCFAbsoluteTime(&catInfo.contentModDate, &cfTime) == noErr)
						{
							CFDateRef dateRef = nil;
							dateRef = CFDateCreate(kCFAllocatorDefault, cfTime);
							if (dateRef != nil)
							{
								NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
								[formatter setTimeStyle:NSDateFormatterNoStyle];
								[formatter setDateStyle:NSDateFormatterShortStyle];
								
								NSString * modDateStr = [formatter stringFromDate:(NSDate*)dateRef];
								
							    infoDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
												  [filePath lastPathComponent], @"name",
												  [filePath pathExtension], @"extension",
												  modDateStr, @"modified",
												  [NSString stringWithFormat:@"%ld", catInfo.dataPhysicalSize ], @"size",
												  nil];
								NSLog(@"modified Date %@",modDateStr);
								NSLog(@"Size %ld", catInfo.dataPhysicalSize);
								CFRelease(dateRef);
							}
						}
					}		
				}

				[tv setDropRow:[tv numberOfRows] dropOperation:NSTableViewDropAbove];
				
				foundMP3 = YES;
			}
		}
	}
	if (foundMP3) 
	{		
		return NSDragOperationCopy; 
	} else {
		
		return NSDragOperationNone; 
	}
	
}

- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)op
{
    // Get the drag-n-drop pasteboard
    NSPasteboard *myPasteboard=[info draggingPasteboard];

	NSArray *typeArray=[NSArray arrayWithObjects:DragDropAudioPboardType,NSFilenamesPboardType,nil];
	
    NSString *filePath, *availableType,*lastPathOfFileName;
    NSArray *filesList;
    int i;
	
    // find the best match of the types we'll accept and what's actually on the pasteboard
    availableType=[myPasteboard availableTypeFromArray:typeArray];

    filesList=[myPasteboard propertyListForType:availableType];
	
    for (i=0;i<[filesList count];i++)
    {
        filePath=[filesList objectAtIndex:i];
		lastPathOfFileName=[filePath lastPathComponent];
		[songsFullPath insertObject:filePath atIndex:row+i];

	    [tableRecordsArray insertObject:infoDictionary  atIndex:row+i];
		
    }

    [songTable reloadData];

    [songTable selectRow:row+i-1 byExtendingSelection:NO];
    return YES;
}

- (IBAction)playSong:(id)sender
{

	int i;
	NSString *selectFilePath,*fullPath,*lastPath;
	if (isRunning)
		[self stopPlaying:nil];
	
	selectFilePath = [tableRecordsArray objectAtIndex:[songTable selectedRow]]; 
	NSLog(@"this is %@.",selectFilePath);
	for(i=0;i<[songsFullPath count];i++)
		
	{   
		 fullPath=[songsFullPath objectAtIndex:i];
		 NSLog(@"this is %@.",fullPath);
		 lastPath=[fullPath lastPathComponent];
		if([selectFilePath isEqualToString:lastPath])
		{

			movieSound = [[QTMovie movieWithFile:fullPath error:NULL] retain];

			break;
		}
	}

		[movieSound play];

	  isRunning =YES;
}

// It's time to stop playing a song now
-(IBAction)stopPlaying:(id)sender
{
    if (isRunning)
    {

		[movieSound stop];
        isRunning=NO;
    }
}

-(void)dealloc
{
	[tableRecordsArray release];
	[songsFullPath release];
	[super dealloc];
}

@end