//
//  GRTShellController.mm
//  MySQLWorkbench
//
//  Created by Alfredo Kojima on 23/Sep/08.
//  Copyright 2008 Sun Microsystems Inc. All rights reserved.
//

#import "GRTShellController.h"
#import "GRTShellViewController.h"

#import "sigobjc++.h"

#include "grt/grt_manager.h"

#include "interfaces/interfaces.h"

@implementation GRTShellController

static void handle_message(const grt::Message &msg, GRTShellViewController *shell)
{
  [shell handleGRTMessage: &msg];
}


static void handle_error(const std::string &title, const std::string &text, GRTShellViewController *shell)
{
  [shell writeLine:[NSString stringWithCPPString: strfmt("%s: %s", title.c_str(), text.c_str())]];
}


- (void)awakeFromNib
{
  _grtm= new bec::GRTManager(true);

  register_interfaces(_grtm->get_grt());

  [shell loadSidebar];
  
  [shell setupWithGRTManager: _grtm];
  
  [sidebarPlaceholder addSubview:[shell sidebar]];
  [[shell sidebar] setFrame:NSMakeRect(0, 0, [sidebarPlaceholder size].width, [sidebarPlaceholder size].height)];
    
  _grtm->set_message_callback(sigc::bind(sigc::ptr_fun(handle_message), shell));

  _grtm->set_error_callback(sigc::bind(sigc::ptr_fun(handle_error), shell));
  
  bec::IconManager::get_instance()->set_basedir([[[NSBundle mainBundle] resourcePath] UTF8String]);
  bec::IconManager::get_instance()->add_search_path("images");
  _grtm->set_search_paths("modules", 
                          [[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/grt"] UTF8String], 
                          "libraries");
  _grtm->initialize();
  
  _grtm->perform_idle_tasks();

  [shell refresh];

  _idleTimer= [NSTimer scheduledTimerWithTimeInterval:0.25 
                                               target:self selector:@selector(doIdleStuff:) userInfo:nil 
                                              repeats:YES];
}


- (void)dealloc
{
  if (_idleTimer)
  {
    [_idleTimer invalidate];
    [_idleTimer release];
  }
  delete _grtm;
  [super dealloc];
}


- (void)doIdleStuff:(NSTimer*)timer
{
  _grtm->perform_idle_tasks();
}

@end
