#import "SearchViewController.h"
#import "PlaylistViewController.h"
#import "MainViewController.h"
#import "AppDelegate.h"

@implementation SearchViewController

#if TARGET_IPAD
- (CGSize)contentSizeForViewInPopoverView {
    return CGSizeMake(320.0, 440.0);
}
#endif

- (void)viewDidLoad
{
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  self.navigationItem.title = @"Search";
}

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

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

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

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [textField resignFirstResponder];
  Playlist *playlist = [[Playlist alloc] initWithName:textField.text abc:abcSearchText.text title:titleSearchText.text key:keySearchText.text meter:meterSearchText.text database:appDelegate.database];

  MainViewController *controller = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
  controller.playlist = playlist;
#if TARGET_IPAD
	[self.navigationController pushViewController:controller animated:YES];
#else
	[appDelegate.navigationController pushViewController:controller animated:YES];
#endif
  return YES;
}

- (void)keyboardWillShow:(NSNotification *)notification
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if ( !self.view.hidden )
    appDelegate.topViewController.navigationItem.rightBarButtonItem = cancelButton;
}

- (void)keyboardWillHide:(id)sender
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if ( !self.view.hidden )
    appDelegate.topViewController.navigationItem.rightBarButtonItem = nil;
}

- (void)cancelPressed:(id)sender
{
  [abcSearchText resignFirstResponder];
  [titleSearchText resignFirstResponder];
  [keySearchText resignFirstResponder];
  [meterSearchText resignFirstResponder];
}

@end
