#import <Foundation/NSDictionary.h>

#import "GreenstoneApplication.h"
#import "GreenstoneButtonBar.h"

#import "GreenstoneAPI.h"

static GreenstoneApplication* _toplevelApp   = nil;
static UITransitionView*      _transView     = nil;
static SimpleWebView*         _webView       = nil;
static GreenstoneAPI*         _greenstoneAPI = nil;

static NSString* _inCollection = nil;
static NSMutableDictionary* _collectionToRowId = nil;

@implementation GreenstoneApplication

+(GreenstoneApplication*) toplevelApp {
  return (_toplevelApp);
}

+(GreenstoneAPI*) greenstoneAPI {
  return (_greenstoneAPI);
}

+(CGRect)workAreaRect
{
  CGRect screen_rect = [UIHardware fullScreenApplicationContentRect];

  int wa_x_dim = screen_rect.size.width;
  int wa_y_dim = screen_rect.size.height - BOT_NAVBAR_HEIGHT;

  CGRect wa_rect = CGRectMake(0.0f,0.0f,wa_x_dim,wa_y_dim);

  return wa_rect;
}


+(void) setInCollection:(NSString*)collection
{
  NSLog(@"Setting in collection = %@",collection);
  if (_inCollection != nil) {
    // [_inCollection release]; // **** memory leak????
  }
  _inCollection = nil;
    
  if (collection != nil) {
    _inCollection = [[NSString alloc] initWithString:collection];
  }
}

+(int) inCollectionRowId
{
  if (_inCollection == nil) {
    return -1;
  }

  NSNumber* rowid_num = [_collectionToRowId objectForKey:_inCollection];
  int rowid = [rowid_num intValue];

  return rowid;
}

-(NSString*) languagePref
{
  int rowid = [GreenstoneApplication inCollectionRowId];

  if (rowid>=0) {

    PrefView* prefview = (PrefView*)[_prefCascadeView directEntry:rowid];
    NSString* lang = [prefview languagePref];

    return lang; // lang is allocated, make sure calling method does release
  }
  else {
    return nil;
  }
}



-(void) applicationDidFinishLaunching:(NSNotification *)aNotification
{
    _toplevelApp = self;
    _greenstoneAPI = new GreenstoneAPI(self);

    _inCollection = nil;
    _collectionToRowId = nil;

    if (!_greenstoneAPI->sanityCheck()) {
      return;
    }

    CGRect screen_rect = [UIHardware fullScreenApplicationContentRect];
    screen_rect.origin.x = screen_rect.origin.y = 0.0f;

    _window = [[UIWindow alloc] initWithContentRect: screen_rect];

    CGRect workarea_rect = [GreenstoneApplication workAreaRect];

    // Set up top-level browsing and search menu CascadeViews
    _browseCascadeView = [BrowseCascadeView alloc];
    _browseCascadeView = [_browseCascadeView initWithFrame:workarea_rect withTitle: @"Browse collection:"];

    _queryCascadeView = [QueryCascadeView alloc];
    _queryCascadeView = [_queryCascadeView initWithFrame:workarea_rect withTitle: @"Search collection:"];

    _prefCascadeView = [PrefCascadeView alloc];
    _prefCascadeView = [_prefCascadeView initWithFrame:workarea_rect withTitle: @"Collection preferences:"];

    NSMutableArray* collist = _greenstoneAPI->collectionList();

    int collist_len = [collist count];
    _collectionToRowId = [[NSMutableDictionary alloc] initWithCapacity:collist_len];

    NSEnumerator* collist_enumerator = [collist objectEnumerator];
    int i = 0;
    NSString* colnamedir;
    while (colnamedir = [collist_enumerator nextObject]) {
      ColInfoResponse_t& colinfo = _greenstoneAPI->collectInfo(colnamedir);
      NSString* colname = _greenstoneAPI->collectionName(colinfo);

      [_browseCascadeView appendMenuItem:self withItem:colname withGID:colnamedir];
      [_queryCascadeView appendMenuItem:self withItem:colname withGID:colnamedir];
      [_prefCascadeView appendMenuItem:self withItem:colname withGID:colnamedir];

      NSNumber* inum = [[NSNumber alloc] initWithInt: i];
      [_collectionToRowId setObject:inum forKey:colnamedir];
      [inum release]; // **** should probably add this in

      i++;
    }
    [collist release];

    
    if (_webView == nil) {
      // setup Web browser view
      _webView = [[SimpleWebView alloc] initWithFrame:workarea_rect];
    }

    if (_transView == nil) {
      // Set up transition view
      _transView = [[UITransitionView alloc] initWithFrame: workarea_rect];
    }

    // Set up button bar
    int butbar_x_org = 0.0f;
    int butbar_y_org = workarea_rect.size.height+1;
    int butbar_x_dim = screen_rect.size.width;
    int butbar_y_dim = BOT_NAVBAR_HEIGHT;

    CGRect butbarrect = CGRectMake(butbar_x_org,butbar_y_org,butbar_x_dim,butbar_y_dim);
    _butbar = [[GreenstoneButtonBar alloc] initInView:_window withFrame:butbarrect];

    // Usual standard window stuff
    [_window orderFront: self];
    [_window makeKey: self];
    [_window _setHidden: NO];

    [_window addSubview: _transView ];
    [_window addSubview: _butbar]; 

    [_transView transition:0 toView:_browseCascadeView];
}


enum compassDirection { itNorth=0, itEast=1, itSouth=2, itWest=3};

static int compass_degrees[4] = { 0, 90, 180, 270 };

static int current_orientation = kOrientationVertical;
static int current_compass_dir = itNorth;
static int current_compass_degs = 0;

-(void) deviceOrientationChanged:(struct __GSEvent *)event
{
    int new_orientation = [UIHardware deviceOrientation: YES];
    
    int new_compass_dir  = -1;

    switch (new_orientation) 
    {
      case kOrientationVertical:
	new_compass_dir = itNorth;
	break;

      case kOrientationHorizontalLeft:
	new_compass_dir = itEast;
	break;

      case kOrientationHorizontalRight:
	new_compass_dir = itWest;
	break;
      case kOrientationVerticalUpsideDown:
	new_compass_dir = itSouth;
	break;	
    }

    if (new_compass_dir>=0) {
      int new_compass_degs = compass_degrees[new_compass_dir];
      int degs_delta = current_compass_degs - new_compass_degs;

      if (degs_delta != 0) {

	current_orientation  = new_orientation;
	current_compass_degs = new_compass_degs;
	current_compass_dir  = new_compass_dir;
	
	[_webView setTransform:CGAffineTransformIdentity];
	[_webView setRotationBy:new_compass_degs];	
      }
    }

    [super deviceOrientationChanged:event];
}



-(void) buttonBarClicked:(id)sender 
{
    int button = [sender tag];
    int transStyle = UITransitionNextShiftUp;

    int rowid = [GreenstoneApplication inCollectionRowId];

    switch (button) 
    {
      case GSBBBrowse:
	if (rowid>=0) {
	  [_transView transition:transStyle toView:[_browseCascadeView directEntry:rowid]];
	}
	else {
	  [_transView transition:transStyle toView:_browseCascadeView];
	}
	break;

      case GSBBQuery:
	if (rowid>=0) {
	  [_transView transition:transStyle toView:[_queryCascadeView directEntry:rowid]];
	}
	else {
	  [_transView transition:transStyle toView:_queryCascadeView];
	}
	break;

      case GSBBPref:
	if (rowid>=0) {
	  [_transView transition:transStyle toView:[_prefCascadeView directEntry:rowid]];
	}
	else {
	  [_transView transition:transStyle toView:_prefCascadeView];
	}
	break;

      default:
	NSLog(@"Unrecognised button bar click: %d",button);
	break;
    }
}


+(void) transitionView:(int)eventNum fromView:(UIView*)from toView:(UIView*)to
{
  [_transView transition:eventNum fromView:from toView:to];
}

+(void) startWebViewBusy
{
  // cerr << "**** start busy" << endl;
  // stub for providing "busy" cue (e.g. busy spinner, or HUD)
}

+(void) stopWebViewBusy
{
  // cerr << "**** end busy" << endl;
  // stub for providing "busy" cue (e.g. busy spinner, or HUD)
}

+(void) loadURL:(NSURL*)url
{
  [_webView loadURL:url];
}

+(void) showWebView:(int)eventNum  fromView:(UIView*)from withURL:(NSURL*)url
{
  [_webView loadURL:url];
  [_webView setParent:from];
  [_transView transition:eventNum fromView:from toView:_webView];
}



-(void) alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{	
    [sheet dismissAnimated:YES];
    [sheet release];
}


-(void) dealloc
{
    [_browseCascadeView release];
    [_queryCascadeView release];
    [_prefCascadeView release];

    [_window release];
    [_butbar release];

    [super dealloc];
}


@end



