﻿// Copyright (C) 2007 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alexander Ilyin
// Created:    2007.08.27

ensureNamespace("Xtensive");

// cfg should contain
//    gridPanel
//    argumentType : 'object' | 'array'
//    dataIndex : '.| data | json | {recordName}
//
Xtensive.GridCommandArgument = function(cfg) {
  Xtensive.GridCommandArgument.initializeBase(this, [cfg]);
  this.gridPanel = cfg.gridPanel;
  this.argumentType = cfg.argumentType || 'object';
  this.dataIndex = cfg.dataIndex || '.';
}

Xtensive.GridCommandArgument.prototype = {
  init: function() {
    this.sm = this.gridPanel.getSelectionModel();
    this.sm.on('selectionchange', this.__onSelectionChange, this);
  },

  get_Available: function() {
    if (this.argumentType == 'object')
      return this.sm.getCount() == 1;
    if (this.argumentType == 'array')
      return this.sm.getCount() != 0;
  },

  get_Value: function() {
    if (this.argumentType == 'object')
      return this.extractValue(this.sm.getSelected());

    if (this.argumentType == 'array') {
      var result = [];
      var selectedRecords = this.sm.getSelections();
      for (var i = 0; i < selectedRecords.length; i++)
        result.push(this.extractValue(selectedRecords[i]));
      return result;
    }
  },

  extractValue: function(record) {
    if (record) {
      if (this.dataIndex == '.' || this.dataIndex == 'data')
        return record.data;
      else if (this.dataIndex == 'json')
        return record.json;
      else if (this.dataIndex)
        return record.get(this.dataIndex);
    }
  },

  __onSelectionChange: function() {
    this.on_availableChanged();
  }
}
Xtensive.GridCommandArgument.registerClass('Xtensive.GridCommandArgument', Xtensive.CommandArgument);

if (typeof (Sys) !== 'undefined')
  Sys.Application.notifyScriptLoaded();