
#import <Foundation/Foundation.h>

#import <UIKit/CDStructures.h>
#import <UIKit/UIKit.h>
#import <UIKit/UITable.h>
#import <UIKit/UIProgressIndicator.h>

#import "GreenstoneApplication.h"
#import "GreenstoneAPI.h"
//#import "SimpleWebView.h"
#import "GSResultItem.h"

#import "BrowseCascadeView.h"

// ***** think about coding for orientation of iPod!!!!

@implementation BrowseCascadeView


-(UIView*) directEntry:(int)rowId
{
  return self;
}


-(void) browseListToMenuItems:(NSMutableArray*)browseList withCollection:(NSString*)collection withGID:(NSString*)gid
{  
  GreenstoneAPI* greenstoneAPI = [GreenstoneApplication greenstoneAPI];

  NSEnumerator* browselist_enumerator = [browseList objectEnumerator];
  NSString* childname;
  while (childname = [browselist_enumerator nextObject]) {
    NSString* childGID = [NSString alloc];

    if (gid==nil) {
      childGID = [childGID initWithString:childname];
    }
    else if ([childname hasPrefix:@"."]==NO) {
      childGID = [childGID initWithString:childname];
    }
    else {
      childGID = [childGID initWithFormat:@"%@%@",gid,childname]; 
    }

    GreenstoneApplication* toplevelApp = [GreenstoneApplication toplevelApp];
    NSString* lang = [toplevelApp languagePref];
    //greenstoneAPI->setLanguage(lang); // *****
    greenstoneAPI->setLanguage("en"); 

    // look up Title metadata for child's GID, and use that to display on menu
    NSString* textTitle = nil;
    if ([childGID hasPrefix:@"CL"]==YES) {
      textTitle = greenstoneAPI->getMetadataFirst(collection,childGID,@"Title");
    }
    else {
      // Try for dc.Title first as generally better quality than ex.Title
      textTitle = greenstoneAPI->getMetadataFirst(collection,childGID,@"dc.Title");
      if (textTitle == nil) {
	textTitle = greenstoneAPI->getMetadataFirst(collection,childGID,@"Title");
      }
    }

    [(BrowseCascadeView*)_childMenu appendMenuItem:self withItem:textTitle withGID:childGID];      

  }
}

-(void) createChildMenu:(NSString*)collection withTitle:(NSString*)title withGID:(NSString*)gid 
            withBrowseList:(NSMutableArray*) browseList
{
  CGRect rect = [GreenstoneApplication workAreaRect];  

  // The following check isn't strictly necessary, if _childMenu is released and set to nil
  // when you transition back to the parent
  if (_childMenu != nil) {
    // [_childMenu release];  // *****
  }

  _childMenu = [BrowseCascadeView alloc];
  _childMenu = [(BrowseCascadeView*)_childMenu initWithFrame:rect withParent:self withCollection:collection withTitle:title withGID:gid]; 

  [self browseListToMenuItems:browseList withCollection:collection withGID:gid];
}



-(void) tableRowSelected:(NSNotification*)notification
{
  UITable* table = [notification object];
  int rowId = [table selectedRow];

  UITableCell* cell = [table cellAtRow:rowId column:0];
  [cell setSelected:FALSE withFade:TRUE];


  GreenstoneAPI* greenstoneAPI = [GreenstoneApplication greenstoneAPI];
  NSString* childTitle = [[_oidItem objectAtIndex:rowId] title];
  int transStyle = UITransitionBothShiftLeft;

  GreenstoneApplication* toplevelApp = [GreenstoneApplication toplevelApp];
  NSString* lang = [toplevelApp languagePref];
  //greenstoneAPI->setLanguage(lang); // ***** make it a param (with default) to calling fns
  greenstoneAPI->setLanguage("en");

  // Initialise with child menu

  if (_collection == nil) {
    // Root node to Browse Greenstone collections
    NSString* childGID = [[_oidItem  objectAtIndex:rowId] oid]; 

    NSString* chosenCollection = [[NSString alloc] initWithString:childGID];

    NSMutableArray* classifierList = greenstoneAPI->browseToplevelList(chosenCollection);
    [self createChildMenu:chosenCollection withTitle:childTitle withGID:nil withBrowseList:classifierList];
    [classifierList release]; 

    [GreenstoneApplication setInCollection:chosenCollection];
    [GreenstoneApplication transitionView:transStyle fromView:self toView:_childMenu];
  }
  else {
    NSString* childGID = [[_oidItem  objectAtIndex:rowId] oid]; 

    if ([childGID hasPrefix:@"CL"]==YES) {
      // Note this test is potentially flawed if a document ID starts CL...
      // Allow this for now, since default is for it to be HASH 

      NSMutableArray* classifierList = greenstoneAPI->browseClassifierList(_collection,childGID);

      NSString* chosenCollection = [[NSString alloc] initWithString:_collection];
      [self createChildMenu:chosenCollection withTitle:childTitle withGID:childGID withBrowseList:classifierList];
      [classifierList release]; 

      [GreenstoneApplication transitionView:transStyle fromView:self toView:_childMenu];
    }
    else {
      NSString* childGID = [[_oidItem  objectAtIndex:rowId] oid]; 

      NSString* srcurl = greenstoneAPI->getSrcUrlMetadata(_collection,childGID);
      NSURL* url = [NSURL alloc];

      if (srcurl == nil) {

	NSTimer *timer = [ NSTimer scheduledTimerWithTimeInterval: 1.0 // used to be 0.3, then 0.5
			 target: self
			 selector: @selector(asynchronousLoad:)
			 userInfo: childGID
			 repeats: NO ];

	url = [url initWithString:@"file:///var/code/gs2-runtime-svn/ext/iOS3.x/loading.html"]; // **** make it use proper gsdlhome

      }
      else {
	NSString* fullurlstr = [[NSString alloc] initWithFormat:@"file://%@",srcurl];

	url = [url initWithString:fullurlstr];
	NSLog(@"** opening src URL= %@",fullurlstr);

      }
      [GreenstoneApplication showWebView:transStyle fromView:self withURL:url];

    }
  }
}




-(void) asynchronousLoad:(NSTimer*)timer
{
  NSString* childGID = [timer userInfo];

  [GreenstoneApplication startWebViewBusy];

  GreenstoneAPI* greenstoneAPI = [GreenstoneApplication greenstoneAPI];
  GreenstoneApplication* toplevelApp = [GreenstoneApplication toplevelApp];
  NSString* lang = [toplevelApp languagePref];
  //greenstoneAPI->setLanguage(lang); // ***** make param
  greenstoneAPI->setLanguage("en"); 

  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 loadURL:url];
  // [GreenstoneApplication showWebView:0 fromView:self withURL:url]; // ****

  [GreenstoneApplication stopWebViewBusy];
}


-(void) navigationBar:(UINavigationBar*)navbar buttonClicked:(int)button 
{
  NSLog(@"_gid = %@",_gid);

  switch (button) 
  {
    case 1:  // left button (back)
      // if ([_gid hasPrefix:@"CL"]==YES) { // ****
      if (_gid == nil) {
	[GreenstoneApplication setInCollection:nil];
      }
      break;
  }

  [super navigationBar:navbar buttonClicked:button];
}
@end
