#import "WebViewController.h"
#import "ImportProgressController.h"
#import "BrowserViewController.h"

@implementation WebViewController

@synthesize urlField;
@synthesize webView;
@synthesize activityIndicator;
@synthesize currentURLRequest;

- (void)viewDidLoad
{
  urlField.delegate = self;
  webView.delegate = self;

	NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
	NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
	NSString *htmlString = [[NSString alloc] initWithData:[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
	
  UIImage *image = [UIImage imageNamed:@"bonjour.png"];
  UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(showBonjourBrowser:)];//FIXME
  self.navigationItem.rightBarButtonItem = item;

  webView.delegate = self;
	[self.webView loadHTMLString:htmlString baseURL:nil];
	[htmlString release];
  activityIndicator.hidden = YES;

//  backButton.enabled = NO;
//  forwardButton.enabled = NO;
}

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  return YES;
}

- (void) browserViewController:(BrowserViewController*)bvc didResolveInstance:(NSNetService*)ref
{
  [[self navigationController] popViewControllerAnimated:YES];
  NSString *s = [NSString stringWithFormat:@"http://%@:%d", [ref hostName], [ref port]];
  NSURL *url = [NSURL URLWithString:s];
  [urlField setText:s];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  [self.webView loadRequest:request];
}

- (IBAction)showBonjourBrowser:(id)sender
{
  BrowserViewController *controller = [[BrowserViewController alloc] initWithTitle:@"Bonjour" showDisclosureIndicators:NO showCancelButton:YES];
  controller.delegate = self;
#if TARGET_IPAD
  UIPopoverController* popover = [[UIPopoverController alloc] initWithContentViewController:controller];
  [popover setPopoverContentSize:CGSizeMake(320, 480) animated:NO];
  [popover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
#else
  [[self navigationController] pushViewController:controller animated:YES];
#endif
  [controller searchForServicesOfType:@"_http._tcp." inDomain:@"local"];
  [controller autorelease];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
  NSURL *url = [request URL];
  if ( url ) {
    [urlField setText:[url absoluteString]];
    NSString *path = [url path];
    if ( path ) {
      NSString *extension = [path pathExtension];
      self.currentURLRequest = request;
      // thesession.org has URLs like "tunes/27/abc"
      if ( [extension length] == 0 )
        extension = [path lastPathComponent];
      if ( extension && [extension caseInsensitiveCompare:@"abc"] == 0 ) {
        UIActionSheet *sheet = [[UIActionSheet alloc]
          initWithTitle:[NSString stringWithFormat:@"Import tunes from '%@'?", [path lastPathComponent]]
          delegate:self
          cancelButtonTitle:@"Cancel"
          destructiveButtonTitle:@"Import"
          otherButtonTitles:nil
        ];
        [sheet showInView:self.view];
        return NO;
      }
    }
  }
  return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
  [urlField resignFirstResponder];
  NSURL *url = [NSURL URLWithString:[urlField text]];
  if ( [url scheme] == nil )
    url = [NSURL URLWithString:[@"http://" stringByAppendingString:[urlField text]]];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  [self.webView loadRequest:request];
  return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
  activityIndicator.hidden = NO;
  [activityIndicator startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)view
{
  [activityIndicator stopAnimating];
  activityIndicator.hidden = YES;
  backButton.enabled = view.canGoBack;
  forwardButton.enabled = view.canGoForward;
  importButton.enabled = currentURLRequest != nil;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
}

- (IBAction) back:(id)sender
{
  [webView goBack];
}

- (IBAction) forward:(id)sender
{
  [webView goForward];
}

- (IBAction) importABC:(id)sender
{
  ImportProgressController *controller = [[ImportProgressController alloc] initWithNibName:@"ImportProgress" bundle:nil];
  [self presentModalViewController:controller animated:YES];
  [controller importRequest:currentURLRequest];
  [currentURLRequest release];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if ( buttonIndex == 0 ) {
    ImportProgressController *controller = [[ImportProgressController alloc] initWithNibName:@"ImportProgress" bundle:nil];
    [self presentModalViewController:controller animated:YES];
    [controller importRequest:currentURLRequest];
    [currentURLRequest release];
  }
}

#if TARGET_IPAD
- (IBAction) donePressed:(id)sender
{
  [self dismissModalViewControllerAnimated:YES];
}
#endif

@end
