//
//  RoleEditor.mm
//  MySQLWorkbench
//
//  Created by Alfredo Kojima on 23/Feb/09.
//  Copyright 2009 Sun Microsystems Inc. All rights reserved.
//

#import "RoleEditor.h"

#import "MCPPUtilities.h"

#import "GRTTreeDataSource.h"

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



@implementation RolePrivilegeObjectListDataSource

- (void)setRoleEditor:(DbMysqlRoleEditor*)owner
{
  mOwner= owner;
}


- (void)setBackEnd:(bec::RoleEditorBE*)be
{
  mBackEnd= be;
}


- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
  bec::NodeId node;
  NSInteger row= [[aNotification object] selectedRow];
  
  if (row >= 0)
    node.append(row);
  
  mBackEnd->get_object_list()->set_selected_node(node);
  
  [mOwner refresh];
}


- (NSDragOperation)tableView:(NSTableView*)tv
                validateDrop:(id <NSDraggingInfo>)info
                 proposedRow:(int)row
       proposedDropOperation:(NSTableViewDropOperation)op
{
  if ([[[info draggingPasteboard] types] containsObject: @"x-mysql-wb/db.DatabaseObject"])
    return NSDragOperationGeneric;
  
  return NSDragOperationNone;
}


- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info
              row:(int)row dropOperation:(NSTableViewDropOperation)operation
{  
  NSPasteboard *pboard= [info draggingPasteboard];
  NSString *data= [pboard stringForType:@"x-mysql-wb/db.DatabaseObject"];
  return mBackEnd->add_dropped_objectdata([data UTF8String]);
}

@end


// --------------------------------------------------------------------------------------------------


@implementation RolePrivilegeListDataSource

- (void)setListModel:(bec::RolePrivilegeListBE*)be
{
  mList= be;
}


- (void)setRoleEditor:(DbMysqlRoleEditor*)owner
{
  mOwner= owner;
}


- (IBAction)uncheckAll:(id)sender
{
  mList->remove_all();

  [mOwner refresh];
}


- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  if (mList)
  {
    int enabled;
    mList->get_field(rowIndex, bec::RolePrivilegeListBE::Enabled, enabled);
    
    return [NSNumber numberWithInt: enabled];
  }
  return nil;
}


- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  mList->set_field(rowIndex, bec::RolePrivilegeListBE::Enabled, [anObject integerValue]);
}


- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
  if (mList)
    return mList->count();
  return 0;
}


- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  std::string value;
  
  mList->get_field(rowIndex, bec::RolePrivilegeListBE::Name, value);
  
  [aCell setTitle: [NSString stringWithCPPString: value]];
}

@end

// --------------------------------------------------------------------------------------------------

@implementation DbMysqlRoleEditor

static void call_refresh(DbMysqlRoleEditor *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:@"RoleEditor"
                                           externalNameTable:[NSDictionary dictionaryWithObject:self forKey:NSNibOwner] 
                                                    withZone:nil])
      NSLog(@"Could not load RoleEditor.xib");
    
    [self setMinimumSize: [tabView frame].size];

    [roleOutline registerForDraggedTypes:[NSArray arrayWithObject:@"x-mysql-wb/controlprivate"]];
    
    // setup the object list for accepting drops
    [objectTable registerForDraggedTypes:[NSArray arrayWithObject:@"x-mysql-wb/db.DatabaseObject"]];
    
    [self reinitWithArguments: args];
  }
  return self;
}


- (void)reinitWithArguments:(const grt::BaseListRef&)args
{
  [super reinitWithArguments: args];
  
  bec::GRTManager* grtm = [self grtManager];
  delete mBackEnd;
  
  mBackEnd= new bec::RoleEditorBE(grtm, db_RoleRef::cast_from(args[0]), get_rdbms_for_db_object(args[0]));
  
  mBackEnd->set_refresh_ui_slot(sigc::bind(sigc::ptr_fun(call_refresh), self));
  
  [objectListDS setBackEnd: mBackEnd];
  
  [roleTreeDS setTreeModel: mBackEnd->get_role_tree()];
  [objectListDS setListModel: mBackEnd->get_object_list()];
  [privilegeListDS setListModel: mBackEnd->get_privilege_list()];
  
  [objectListDS setRoleEditor: self];
  [privilegeListDS setRoleEditor: self];
  
  bec::NodeId roleNode= mBackEnd->get_role_tree()->node_id_for_role(mBackEnd->get_role());
  [roleOutline selectRow: [roleOutline rowForItem:[roleTreeDS itemForNodeId: roleNode]] byExtendingSelection:NO];
  
  // update the UI
  [self refresh];
}


- (void)dealloc
{
  [roleTreeDS release];
  [objectListDS release];
  [privilegeListDS release];

  delete mBackEnd;
  [super dealloc];
}


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


/** Fetches object info from the backend and update the UI
 */
- (void)refresh
{
  if (mBackEnd)
  {
    [nameText setStringValue: [NSString stringWithCPPString: mBackEnd->get_name()]];
    [self updateTitle: [self title]];
    
    [parentPopUp removeAllItems];
    std::vector<std::string> roles(mBackEnd->get_role_list());
    for (std::vector<std::string>::const_iterator iter= roles.begin(); iter != roles.end(); ++iter)
    {
      [parentPopUp addItemWithTitle: [NSString stringWithCPPString: *iter]];
    }
    [parentPopUp selectItemWithTitle: [NSString stringWithCPPString: mBackEnd->get_parent_role()]];    
    [roleOutline reloadData];
    [objectTable reloadData];
    [privilegeTable reloadData];
    [roleOutline expandItem:nil expandChildren:YES];
  }
}


- (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 - Role", mBackEnd->get_name().c_str())];
}


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


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


- (IBAction)selectedParent:(id)sender
{
  mBackEnd->set_parent_role([[parentPopUp titleOfSelectedItem] UTF8String]);
  [roleOutline reloadData];
  [roleOutline expandItem:nil expandChildren:YES];
}


@end
