//
//  MySQLSchemaEditor.mm
//  MySQLWorkbench
//
//  Created by Alfredo Kojima on 11/Jan/09.
//  Copyright 2009 Sun Microsystems Inc. All rights reserved.
//

#import "MySQLSchemaEditor.h"

#import "MCPPUtilities.h"
#include "grtdb/db_object_helpers.h" // get_rdbms_for_db_object()

@implementation DbMysqlSchemaEditor

static void call_refresh(DbMysqlSchemaEditor *self)
{
  [self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:YES];
}


- (id)initWithModule:(grt::Module*)module GRTManager:(bec::GRTManager*)grtm arguments:(const grt::BaseListRef&)args
{
  self= [super initWithModule:module GRTManager:grtm arguments:args];
  if (self != nil)
  {
    // load GUI. Top level view in the nib is the NSTabView that will be docked to the main window
    if (![[NSBundle bundleForClass:[self class]] loadNibFile:@"MySQLSchemaEditor"
                                           externalNameTable:[NSDictionary dictionaryWithObject:self forKey:NSNibOwner] 
                                                    withZone:nil])
        NSLog(@"Could not load MySQLSchemaEditor.xib");
    
    // take the minimum size of the view from the initial size in the nib.
    // Therefore the nib should be designed as small as possible
    // note: the honouring of the min size is not yet implemented
    [self setMinimumSize: [tabView frame].size];
    
    // setup the editor backend with the schema object (args[0])
    mBackEnd= new MySQLSchemaEditorBE(grtm, db_mysql_SchemaRef::cast_from(args[0]), get_rdbms_for_db_object(args[0]));
    
    // fill the collation Popup with the list of supported collations taken from the backend
    MFillPopupButtonWithStrings(collationPopup, mBackEnd->get_charset_collation_list());
    
    // register a callback that will make [self refresh] get called
    // whenever the backend thinks its needed to refresh the UI from the backend data (ie, the
    // edited object was changed from somewhere else in the application)
    mBackEnd->set_refresh_ui_slot(sigc::bind(sigc::ptr_fun(call_refresh), self));
    
    // update the UI
    [self refresh];
  }
  return self;
}


- (void)reinitWithArguments:(const grt::BaseListRef&)args
{
  [super reinitWithArguments: args];
  
  delete mBackEnd;
  
  mBackEnd= new MySQLSchemaEditorBE(_grtm, db_mysql_SchemaRef::cast_from(args[0]), get_rdbms_for_db_object(args[0]));
  
  MFillPopupButtonWithStrings(collationPopup, mBackEnd->get_charset_collation_list());
  
  mBackEnd->set_refresh_ui_slot(sigc::bind(sigc::ptr_fun(call_refresh), self));
  
  // update the UI
  [self refresh];
}


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


/** Fetches object info from the backend and update the UI
 */
- (void)refresh
{
  if (mBackEnd)
  {
    [nameText setStringValue: [NSString stringWithCPPString:mBackEnd->get_name()]];
    
    // select the current value of option "CHARACTER SET - COLLATE" in the collation popup
    [collationPopup selectItemWithTitle: [NSString stringWithCPPString:mBackEnd->get_schema_option_by_name("CHARACTER SET - COLLATE")]];
    
    [commentText setString: [NSString stringWithCPPString:mBackEnd->get_comment()]];
  }
}


- (BOOL)matchesIdentifierForClosingEditor:(NSString*)identifier
{
  return mBackEnd->should_close_on_delete_of([identifier UTF8String]);
}


- (id)identifier
{
  // an identifier for this editor (just take the object id)
  return [NSString stringWithCPPString:mBackEnd->get_object().id()];
}


- (NSString*)title
{
  // the title for the editor
  return [NSString stringWithCPPString: strfmt("%s - Schema", mBackEnd->get_name().c_str())];
}


- (NSView*)dockableView
{
  // the view to be docked to the main window
  return tabView;
}


- (void)activateCollectionItem:(id)sender
{
  if (sender == collationPopup)
  {
    // set the collation and charset of the schema from the selected value
    mBackEnd->set_schema_option_by_name("CHARACTER SET - COLLATE", [[collationPopup titleOfSelectedItem] UTF8String]);
  }
}

- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
  if ([aNotification object] == nameText)
  {
    // set name of the schema
    mBackEnd->set_name([[nameText stringValue] UTF8String]);
    [self updateTitle: [self title]];
  }  
}


- (void)textDidChange:(NSNotification *)aNotification
{
  if ([aNotification object] == commentText)
  {
    // set comment for the schema
    mBackEnd->set_comment([[commentText string] UTF8String]);
  }
}


@end
