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

#import "GRTListDataSource.h"
#include "mysql_table_editor.h"
#import "MTextImageCell.h"
#import "GRTIconCache.h"

@implementation GRTNodeId


+ (GRTNodeId*)nodeIdWithNodeId:(const bec::NodeId&)nodeId
{
  return [[[GRTNodeId alloc] initWithNodeId:nodeId] autorelease];
}


- (id)init
{
  if ((self= [super init]) != nil)
  {
    _nodeId= new bec::NodeId();
  }
  return self;
}


- (id)initWithNodeId:(const bec::NodeId&)nodeId
{
  if ((self= [super init]) != nil)
  {
    _nodeId= new bec::NodeId(nodeId);
  }
  return self;
}


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


- (const bec::NodeId&)nodeId
{
  return *_nodeId;
}


- (BOOL)isEqual:(id)other
{
  if ([other isKindOfClass: [GRTNodeId class]])
    return *_nodeId == [other nodeId];

  return NO;
}

@end


@implementation GRTListDataSource

- (id)initWithListModel:(bec::ListModel*)model
{
  if ((self = [super init]) != nil)
  {
    _list= model;
  }
  return self;
}


- (void)setListModel:(bec::ListModel*)model
{
  _list= model;
}


- (bec::ListModel*)listModel
{
  return _list;
}


- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  if (_list)
  {
    std::string value;
    _list->get_field(rowIndex, [[aTableColumn identifier] integerValue], value);
  
    return [NSString stringWithUTF8String:value.c_str()];
  }
  return nil;
}


- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  if (_list->is_editable(rowIndex))
  {
    int count= _list->count();
    _list->set_field(rowIndex, [[aTableColumn identifier] integerValue], [anObject UTF8String]);
    if (_list->count() > count)
      [aTableView reloadData];
  }
  else if ([anObject isKindOfClass: [NSNumber class]])
  {
    _list->set_field(rowIndex, [[aTableColumn identifier] integerValue], [anObject integerValue]);
  }
}


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


- (BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  return _list->is_editable(rowIndex);
}


- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
  if ([aCell isKindOfClass:[MTextImageCell class]])
  {
    bec::IconId icon_id= _list->get_field_icon(rowIndex, [[aTableColumn identifier] integerValue], bec::Icon16);

    if (icon_id != 0)
    {
      NSImage *image= [[GRTIconCache sharedIconCache] imageForIconId:icon_id];
      [aCell setImage:image];
    }
    else
      [aCell setImage:nil];
  }
}


@end


