#import "PApp.h"
#import "PController.h"
#import "PStatefulMenu.h"
#import "PThreadedFileDiscovery.h"

@interface MovieTrailerDiscovery: PThreadedFileDiscovery
- (void) setEnabledFromMenu: (id) sender;
- (void) restartDiscoveryIn: (NSTimeInterval) anInterval;
@end

@implementation MovieTrailerDiscovery
+ (void) initialize
{
  [[PController sharedController] addFileDiscovery: [[MovieTrailerDiscovery alloc] init]];
}

- (id) init
{
  [super init];

  NSString* yesno = [[[PController sharedController]
		       defaultsForPluginWithName: @"MovieTrailerDiscovery"]
		      objectForKey: @"Enabled"];
  if(!yesno) [self setEnabled: YES];
  else [self setEnabled: [yesno intValue]];

  PStatefulMenu* menu = [[PController sharedController] settingsMenu];
  PStatefulMenuItem* item = [menu addItemWithTitle: @"Apple movie trailers"
				  action: @selector(setEnabledFromMenu:)];
  [item setTarget: self];
  [item setState: enabled ? NSOnState : NSOffState];
  
  return self;
}

- (NSString*) busyTaskDescription
{
  return @"Reading Movie Trailers";
}

- (BOOL) runThread
{
  NSAssert(mainThread != [NSThread currentThread],
	   @"MainThread is current!");
  
  NSError *error;
  NSString *url = @"http://www.apple.com/trailers/home/xml/current.xml";

  NSXMLDocument *doc = [[[NSXMLDocument alloc]
			  initWithContentsOfURL: [NSURL URLWithString: url]
			  options: 0
			  error: &error]
			 autorelease];
  
  if(error)
    {
      NSLog(@"Error reading %@: %@", url, error);
      return NO;
    }
  
  NSXMLElement *root = [doc rootElement];
  NSEnumerator *e1 = [[root children] objectEnumerator];
  NSXMLElement *elem;
  while((elem = [e1 nextObject]))
    {
      if(![[elem name] isEqualToString: @"movieinfo"])
	{
	  NSLog(@"Unknown name %@ in movie description", [elem name]);
	  continue;
	}

      NSArray *infoArr, *posterArr, *previewArr;
      NSXMLElement *info, *poster, *preview;

      infoArr = [elem elementsForName: @"info"];
      if(!infoArr)
	{
	  NSLog(@"Movie info for %@ contains no 'info' node",
		[[elem attributeForName: @"id"] stringValue]);
	  continue;
	}
      else if([infoArr count] != 1)
	{
	  NSLog(@"Movie info for %@ contains %d 'info' nodes instead of 1",
		[[elem attributeForName: @"id"] stringValue],
		[infoArr count]);
	  continue;
	}
      else info = [infoArr objectAtIndex: 0];
		
      posterArr = [elem elementsForName: @"poster"];
      if(!posterArr)
	{
	  NSLog(@"Movie info for %@ contains no 'poster' node",
		[[elem attributeForName: @"id"] stringValue]);
	  continue;
	}
      else if([posterArr count] != 1)
	{
	  NSLog(@"Movie info for %@ contains %d 'poster' nodes instead of 1",
		[[elem attributeForName: @"id"] stringValue],
		[posterArr count]);
	  continue;
	}
      else poster = [posterArr objectAtIndex: 0];
		
      previewArr = [elem elementsForName: @"preview"];
      if(!previewArr)
	{
	  NSLog(@"Movie info for %@ contains no 'preview' node",
		[[elem attributeForName: @"id"] stringValue]);
	  continue;
	}
      else if([previewArr count] != 1)
	{
	  NSLog(@"Movie info for %@ contains %d 'preview' nodes instead of 1",
		[[elem attributeForName: @"id"] stringValue],
		[previewArr count]);
	  continue;
	}
      else preview = [previewArr objectAtIndex: 0];

      NSEnumerator *e2;
      NSString *previewLocation = nil, *contentLocation = nil;
      
      e2 = [[poster children] objectEnumerator];
      while((elem = [e2 nextObject]))
	{
	  if([[elem name] isEqualToString: @"location"])
	    previewLocation = [elem stringValue];
	}

      e2 = [[preview children] objectEnumerator];
      while((elem = [e2 nextObject]))
	{
	  if([[elem name] isEqualToString: @"large"])
	    contentLocation = [elem stringValue];
	}

      if(!previewLocation || !contentLocation) continue;

      NSMutableDictionary *dict = [PCtr fillableInfoForPlayableMediaFileAtPath: contentLocation];
      
      [dict setObject: @"Movie Trailers" forKey: kCategory];
      [dict setObject: previewLocation forKey: kPreviewImageURL];

      NSMutableDictionary *csDict = [NSMutableDictionary dictionary];
      [dict setObject: csDict forKey: kContentSpecificDict];

      // evaluate info dictionary
      e2 = [[info children] objectEnumerator];
      while((elem = [e2 nextObject]))
	{
	  if([[elem name] isEqualToString: @"title"])
	    [dict setObject: [elem stringValue]
		  forKey: kTitle];
	  else if([[elem name] isEqualToString: @"runtime"])
	    [csDict setObject: [elem stringValue]
		    forKey: kRuntime];
	  else if([[elem name] isEqualToString: @"rating"])
	    [csDict setObject: [elem stringValue]
		    forKey: kRating];
	  else if([[elem name] isEqualToString: @"studio"])
	    [csDict setObject: [elem stringValue]
		    forKey: kStudio];
	  else if([[elem name] isEqualToString: @"postdate"])
	    [csDict setObject: [elem stringValue]
		    forKey: kPostDate];
	  else if([[elem name] isEqualToString: @"releasedate"])
	    [csDict setObject: [elem stringValue]
		    forKey: kReleaseDate];
	  else if([[elem name] isEqualToString: @"copyright"])
	    [csDict setObject: [elem stringValue]
		    forKey: kCopyright];
	}

      [self performSelectorOnMainThread: @selector(fileWasDiscovered:)
	    withObject: dict
	    waitUntilDone: NO];
    }
}

- (void) restartDiscoveryIn: (NSTimeInterval) anInterval
{
  [NSTimer scheduledTimerWithTimeInterval: anInterval
	   target: self
	   selector: @selector(startDiscovery)
	   userInfo: nil
	   repeats: NO];
}

- (void) setEnabled: (BOOL) yesno
{
  [super setEnabled: yesno];
  [[[PController sharedController]
     defaultsForPluginWithName: @"MovieTrailerDiscovery"]
    setObject: [NSString stringWithFormat: @"%d", yesno]
    forKey: @"Enabled"];
}

- (void) setEnabledFromMenu: (id) sender
{
  if([sender state] == NSOnState)
    {
      [self setEnabled: NO];
      [sender setState: NSOffState];
    }
  else
    {
      [self setEnabled: YES];
      [sender setState: NSOnState];
    }
}
@end