import React from 'react';
import {Icon, Button, Tooltip, Menu, Dropdown} from 'antd';
import {Link} from 'react-router';

export default function Commands(props) {
	const commands = props.commands;
	const record = props.record;

	const keys = Object.keys(commands);

	const limit = 3;
	let $commands = keys.slice(0, limit).map(renderCommand);
	let $more = null;

	if (keys.length > limit) {
		$commands.pop();
		$more = renderMore(keys.slice(limit - 1, keys.length));
	}
	
	$commands.push($more);

  return (
    <div className="table-controls">
      {$commands}
    </div>
  )

  /**
   * [renderMore description]
   * @param  {[type]} keys [description]
   * @return {[type]}      [description]
   */
  function renderMore(keys) {
  	const $menu = (
  		<Menu>
  			{keys.map(key => {
  				return (
  					<Menu.Item key={`command-menu-${key}`}>
  						{renderCommand(key)}
  					</Menu.Item>
  				)
  			})}
  		</Menu>
  	);

  	return (
  		<Dropdown overlay={$menu} key="drodown">
  			<a className="ant-dropdown-link" href="javascript: void(0);">
		      更多 <Icon type="down" />
		    </a>
  		</Dropdown>
  	)
  }

  /**
   * [renderCommand description]
   * @param  {[type]} key [description]
   * @return {[type]}     [description]
   */
  function renderCommand(key) {
  	const command = commands[key];

    // disabled 
    if (command.shouldDisabled) {
	  	const ret = command.shouldDisabled(record);
	  	if (ret.disabled) {
	  		return Disabled(command, ret.message);
	  	}
    }
  	
  	// custom render
    if (command.render) {
      return command.render(props);
    }

    // default render
   	return Default(command);
  }

  /**
   * [Default description]
   * @param {[type]} command [description]
   */
	function Default(command) {
		 return (
	      <a key={command.name} onClick={ev => {
	        props.execCommand(command.command, command.getParams(record))
	      }}>
	        {command.name}
	      </a>
	    )
	}

	/**
	 * [Disabled description]
	 * @param {[type]} command [description]
	 * @param {[type]} message [description]
	 */
	function Disabled(command, message) {
		return (
			<Tooltip key={command.name} title={message}>
	  		<span>
	  			{command.name}
	  		</span>
	  	</Tooltip>
		)
	}
}
