#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UITextLabel.h>
#import <UIKit/UIDateLabel.h> // For defaultFont.
#import <UIKit/UITable.h>
#import <UIKit/UITableCell.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UISearchField.h>
#import <UIKit/UIFrameAnimation.h>
#import <UIKit/UITransitionView.h>

#import "GreenstoneApplication.h"
#import "SimpleWebView.h"
#import "GSResultItem.h"

#import "QueryView.h"

@implementation SearchTableCell

// ***** is the following needed, or need to be modified? 
- (void) drawContentInRect: (struct CGRect)rect selected: (BOOL) selected
{
  [song_name setHighlighted: selected];
  [artist_name setHighlighted: selected];
  [super drawContentInRect: rect selected: selected];
}

@end


@implementation QueryView

- (id)initWithFrame:(struct CGRect)frame withParent:(UIView*)parent 
       withCollection:(NSString*)collection withTitle:(NSString*)title
{
  self = [super initWithFrame:frame];

  _parent = parent;
  _collection = collection;

  // Create the storage array.
  _cellResultList = [[NSMutableArray alloc] init];
  _oidItem = [[NSMutableArray alloc] init];


  // Create the navigation bar
  int nbr1_x_org = 0;
  int nbr1_y_org = 0;
  int nbr1_x_dim = 320;
  int nbr1_y_dim = TOP_NAVBAR_HEIGHT;

  CGRect navbar1_rect = CGRectMake(nbr1_x_org,nbr1_y_org,nbr1_x_dim,nbr1_y_dim);

  UINavigationBar* navbar1 = [[UINavigationBar alloc] initWithFrame:navbar1_rect];
  [navbar1 showLeftButton:@"Back" withStyle:2 rightButton:nil withStyle:0]; // 2 = arrow left.
  [navbar1 setBarStyle: barstyleBlue]; 
  [navbar1 setDelegate:self];
  [navbar1 enableAnimation];
  [self addSubview: navbar1];

  _navbar = navbar1;
  [self setTitle:title];
  
  // Not sure if a second nav bar is really the way to get a 
  // search box with background seamlessly merged with main nav bar
  // Tried to make 1 navbar high enough for everything, but back 
  // button was alligned to bottom of bar

  int nbr2_x_org = nbr1_x_org;
  int nbr2_y_org = nbr1_y_dim;
  int nbr2_x_dim = nbr1_x_dim;
  int nbr2_y_dim = [UISearchField defaultHeight];

  CGRect navbar2_rect = CGRectMake(nbr2_x_org,nbr2_y_org,nbr2_x_dim,nbr2_y_dim);
  UINavigationBar* navbar2 = [[UINavigationBar alloc] initWithFrame:navbar2_rect];
  [navbar2 showLeftButton:nil withStyle:0 rightButton:nil withStyle:0]; 
  [navbar2 setBarStyle: barstyleBlue]; 
  [navbar2 setDelegate:self];
  [navbar2 enableAnimation];

  [self addSubview: navbar2];

  // Create the search box.

  int sr_x_org = 30;
  int sr_y_org = 0;
  int sr_x_dim =  frame.size.width - (2*30);
  int sr_y_dim = [UISearchField defaultHeight];

  CGRect search_rect = CGRectMake(sr_x_org,sr_y_org,sr_x_dim,sr_y_dim);

  _searchBox = [[UISearchField alloc] initWithFrame:search_rect];
  [_searchBox setClearButtonStyle:2];
  [_searchBox setFont:[UITextLabel defaultFont]];
  [[_searchBox textTraits] setReturnKeyType:6];
  [[_searchBox textTraits] setEditingDelegate:self];
  [[_searchBox textTraits] setAutoCapsType: NO];
  [[_searchBox textTraits] setAutoCorrectionType:1];

  [_searchBox setText:@""];
  [_searchBox setDisplayEnabled:YES];

  [_searchBox becomeFirstResponder];

  // Create the table.
  CGRect table_rect = CGRectMake(0, nbr2_y_org+nbr2_y_dim, frame.size.width, 400);

  _table = [[UITable alloc] initWithFrame:table_rect];
  [self addSubview: _table];

  UITableColumn *col = [[UITableColumn alloc] initWithTitle: @"iMPDclient" identifier: @"column1" width: 320.0f];
  [_table addTableColumn: col];
  [_table setDelegate: self];
  [_table setDataSource: self];
  [_table setSeparatorStyle:1];
  [_table setRowHeight:42.0f];
  

  // Create the keyboard
  int kb_x_org = 0;
  int kb_y_org = 410 - [UIKeyboard defaultSize].height;
  int kb_x_dim = frame.size.width; // ****? what about when landscape
  int kb_y_dim = [UIKeyboard defaultSize].height;
  CGRect kb_rect = CGRectMake(kb_x_org,kb_y_org,kb_x_dim,kb_y_dim);

  _keyboard = [[UIKeyboard alloc] initWithFrame:kb_rect];

  [self addSubview: _keyboard];
  _keyboardVisible = YES;
  
  [navbar2 addSubview:_searchBox];

  return self;
}

-(void) setTitle:(NSString*)title
{
  UINavigationItem* navtitle = [UINavigationItem alloc];
  [_navbar pushNavigationItem: [navtitle initWithTitle:title]];
}


- (void)performQuery:(NSString *)searchtext
{
  GreenstoneAPI* greenstoneAPI = [GreenstoneApplication greenstoneAPI];
  NSMutableArray* resultlist = greenstoneAPI->query(_collection,searchtext);

  [_cellResultList removeAllObjects];
  [_oidItem removeAllObjects];

  if (resultlist != nil) {
    NSEnumerator* resultlist_enumerator = [resultlist objectEnumerator];
    GSResultItem* resultitem;
    while (resultitem = [resultlist_enumerator nextObject]) {

      SearchTableCell* cell = [[SearchTableCell alloc] init];
      
      NSString* resultoid = [resultitem oid];

      NSString* resulttitle = [resultitem title];
      if (resulttitle == nil) {
	// doesn't have a valid title 
	resulttitle = [[NSString alloc] initWithString:@"Unknown Title"];
      }

      NSString* resulturl = [resultitem srcurl];
      if (resulturl == nil) { // **** don't need to do this check now
	// doesn't have a valid srcurl => set as the empty string
	resulturl = [[NSString alloc] initWithString:@""];
      }

      [cell setTitle:resulttitle];
      [_cellResultList addObject:cell];
      [_oidItem addObject:resultitem];

      [cell release];
    }
    [resultlist release];
  }

  // Update the table contents.
  [_table reloadData];
}



//***********
//* Delegates 
//***********

-(void) navigationBar:(UINavigationBar*)navbar buttonClicked:(int)button
{
  switch (button) 
  {
    case 1:  // left
      [GreenstoneApplication setInCollection:nil];
      [GreenstoneApplication transitionView:UITransitionBothShiftRight 
          fromView:self toView:_parent];
      break;

    default:
      NSLog(@"Unrecognised navbar button = %d",button);
      break;
  }
}


- (void)tableRowSelected:(NSNotification*)notification
{
  UITable* table = [notification object];
  int rowId = [table selectedRow];

  SearchTableCell* pCell = [table cellAtRow:rowId column:0];
  [pCell setSelected:FALSE withFade:TRUE];

  GSResultItem* oidItem = [_oidItem objectAtIndex:rowId];

  NSString* oid = [oidItem oid];
  NSString* srcurl = [oidItem srcurl];

  NSURL *url = [NSURL alloc];

  if (srcurl == nil) {

    NSTimer *timer = [ NSTimer scheduledTimerWithTimeInterval: 0.3
			 target: self
			 selector: @selector(asynchronousLoad:)
			 userInfo: oid
			 repeats: NO ];
    url = [url initWithString:@"file:///var/gsdl/loading.html"];

    /* *****
    GreenstoneAPI* greenstoneAPI = [GreenstoneApplication greenstoneAPI];
    NSString* doctext = greenstoneAPI->getResolvedDocument(_collection,oid);
    [doctext writeToFile:@"/tmp/gsdoc.html" atomically:NO encoding:NSUTF8StringEncoding error:nil];

    // make sure file is writable by all 
    // => allows for switching between running from command line and Springboard
    system("chmod a+rw /tmp/gsdoc.html"); 

    url = [url initWithString:@"file:///tmp/gsdoc.html"];
    */

  }
  else {
    NSString* fullurlstr = [[NSString alloc] initWithFormat:@"file://%@",srcurl];
    url = [url initWithString:fullurlstr]; 
  }

  int transStyle = UITransitionBothShiftLeft;   
  [GreenstoneApplication showWebView:transStyle fromView:self withURL:url];

}

-(void) asynchronousLoad:(NSTimer*)timer
{
  // **** This is identical to one in BrowseCascadeMenu
  NSString* childGID = [timer userInfo];

  GreenstoneAPI* greenstoneAPI = [GreenstoneApplication greenstoneAPI];
  NSString* doctext = greenstoneAPI->getResolvedDocument(_collection,childGID);

  [doctext writeToFile:@"/tmp/gsdoc.html" atomically:NO encoding:NSUTF8StringEncoding error:nil];
  NSURL* url = [[NSURL alloc] initWithString:@"file:///tmp/gsdoc.html"];
  system("chmod a+rw /tmp/gsdoc.html"); 

  [GreenstoneApplication showWebView:0 fromView:self withURL:url];
}


- (int) numberOfRowsInTable: (UITable *)table
{
  return [_cellResultList count];
}


- (UITableCell *) table: (UITable *)table cellForRow: (int)row column: (int)col
{
  return [_cellResultList objectAtIndex:row];
}

- (UITableCell *) table: (UITable *)table cellForRow: (int)row column: (int)col reusing: (BOOL) reusing
{
  return [self table: table cellForRow: row column: col];
}

- (void)keyboardInputChangedSelection:(id)whatisthis
{
  // when i tap the search field, hide if keyboard is already there, or show if it isn't
  if (!_keyboardVisible)
    [self ShowKeyboard];
}

-(void)keyboardInput:(id)k shouldInsertText:(id)i isMarkedText:(int)b
{
  if ([i characterAtIndex:0] == 0xA) {
    [self keyboardReturnPressed];

    NSString* query = [_searchBox text];
    [self performQuery:query];
  }
}

- (void)scrollerWillStartDragging:(id)whatisthis
{
  // hide keyboard when start scrolling
  if (_keyboardVisible)
    [self HideKeyboard];
}

// --- KEYBOARD METHODS -----------------------------------------------

- (void)keyboardReturnPressed
{
  [self HideKeyboard];
}

- (void)ShowKeyboard
{
  _keyboardVisible = YES;
  
  CGRect startFrame;
  CGRect endFrame;
  NSMutableArray *animations = [[NSMutableArray alloc] init];
  
  endFrame = CGRectMake(0.0f, 410 - [UIKeyboard defaultSize].height, 320, [UIKeyboard defaultSize].height);
  startFrame = endFrame;
  startFrame.origin.y = 245.0 + 216.;
  
  [_keyboard setFrame:startFrame];
  
  UIFrameAnimation *keyboardAnimation = [[UIFrameAnimation alloc] initWithTarget:_keyboard];
  [keyboardAnimation setStartFrame:startFrame];
  [keyboardAnimation setEndFrame:endFrame];
  [keyboardAnimation setSignificantRectFields:2];
  [keyboardAnimation setDelegate:self];
  [animations addObject:keyboardAnimation];
  [keyboardAnimation release];
  
  [[UIAnimator sharedAnimator] addAnimations:animations withDuration:.5 start:YES];
}

- (void)HideKeyboard
{
  _keyboardVisible = NO;
  
  CGRect startFrame;
  CGRect endFrame;
  NSMutableArray *animations = [[NSMutableArray alloc] init];
  
  startFrame = CGRectMake(0, 410 - [UIKeyboard defaultSize].height, 320, [UIKeyboard defaultSize].height);
  endFrame = startFrame;
  endFrame.origin.y = 245.0 + 216.;
  
  [_keyboard setFrame:startFrame];
  
  UIFrameAnimation *keyboardAnimation = [[UIFrameAnimation alloc] initWithTarget:_keyboard];
  [keyboardAnimation setStartFrame:startFrame];
  [keyboardAnimation setEndFrame:endFrame];
  [keyboardAnimation setSignificantRectFields:2];
  [keyboardAnimation setDelegate:self];
  [animations addObject:keyboardAnimation];
  [keyboardAnimation release];
  
  [[UIAnimator sharedAnimator] addAnimations:animations withDuration:.5 start:YES];
}


-(void) dealloc
{
  [_oidItem release];

  [_collection release];

  [super dealloc];
}

@end

