class EntityReferenceSelectionHandlerViews implements EntityReferenceSelectionHandlerInterface {
  public $field;
  public $instance;
  public $entity;
  public $view;
  
  public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
    return new EntityReferenceSelectionHandlerViews($field, $instance, $entity);
  }
  
  protected function __construct($field, $instance, $entity) {
    $this->field = $field;
    $this->instance = $instance;
    $this->entity = $entity;
  }
  
  public static function settingsForm($field, $instance) {
    $view_settings = empty($field['settings']['handler_settings']['view']) ? '' : $field['settings']['handler_settings']['view'];
    $displays = views_get_applicable_views('entityreference display');
            $entity_info = entity_get_info($field['settings']['target_type']);
    $options = array();
    foreach ($displays as $data) {
      list($view, $display_id) = $data;
      if ($view->base_table == $entity_info['base table']) {
        $options[$view->name . ':' . $display_id] = $view->name . ' - ' . $view->display[$display_id]->display_title;
      }
    }
                    $form['view']['#element_validate'] = array('entityreference_view_settings_validate');
    if ($options) {
      $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
      $form['view']['view_and_display'] = array(
        '#type' => 'select',
        '#title' => t('View used to select the entities'),
        '#required' => TRUE,
        '#options' => $options,
        '#default_value' => $default,
        '#description' => '<p>' . t('Choose the view and display that select the entities that can be referenced.<br />Only views with a display of type "Entity Reference" are eligible.') . '</p>',
      );
      $default = !empty($view_settings['args']) ? implode(', ', $view_settings['args']) : '';
      $description = t('Provide a comma separated list of arguments to pass to the view.') . '<br />' . t('This field supports tokens.');
      $form['view']['args'] = array(
        '#type' => 'textfield',
        '#title' => t('View arguments'),
        '#default_value' => $default,
        '#required' => FALSE,
        '#description' => $description,
        '#maxlength' => '512',
      );
            $info = entity_get_info($instance['entity_type']);
      $form['view']['tokens'] = array(
        '#theme' => 'token_tree',
        '#token_types' => array($info['token type']),
        '#global_types' => TRUE,
        '#click_insert' => TRUE,
        '#dialog' => TRUE,
      );
    }
    else {
      $form['view']['no_view_help'] = array(
        '#markup' => '<p>' . t('No eligible views were found. <a href="@create">Create a view</a> with an <em>Reference</em> display, or add such a display to an <a href="@existing">existing view</a>.', array(
          '@create' => url('admin/structure/views/add'),
          '@existing' => url('admin/structure/views'),
        )) . '</p>',
      );
    }
    return $form;
  }
  protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
    $view_name = $this->field['settings']['handler_settings']['view']['view_name'];
    $display_name = $this->field['settings']['handler_settings']['view']['display_name'];
    $args = $this->field['settings']['handler_settings']['view']['args'];
    $entity_type = $this->field['settings']['target_type'];
        $this->view = views_get_view($view_name);
    if (!$this->view || !isset($this->view->display[$display_name]) || !$this->view->access($display_name)) {
      watchdog('entityreference', 'The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']), WATCHDOG_WARNING);
      return FALSE;
    }
    $this->view->set_display($display_name);
    $this->view->pre_execute();
        $this->view->is_cacheable = FALSE;
        $entityreference_options = array(
      'match' => $match,
      'match_operator' => $match_operator,
      'limit' => $limit,
      'ids' => $ids,
    );
    $this->view->display_handler->set_option('entityreference_options', $entityreference_options);
    return TRUE;
  }
  
  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $display_name = $this->field['settings']['handler_settings']['view']['display_name'];
    $args = $this->handleArgs($this->field['settings']['handler_settings']['view']['args']);
    $result = array();
    if ($this->initializeView($match, $match_operator, $limit)) {
            $result = $this->view->execute_display($display_name, $args);
    }
    $return = array();
    if ($result) {
      $target_type = $this->field['settings']['target_type'];
      $entities = entity_load($target_type, array_keys($result));
      foreach ($entities as $entity) {
        list($id, , $bundle) = entity_extract_ids($target_type, $entity);
        $return[$bundle][$id] = $result[$id];
      }
    }
    return $return;
  }
  
  function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $this->getReferencableEntities($match, $match_operator);
    return $this->view->total_items;
  }
  function validateReferencableEntities(array $ids) {
    $display_name = $this->field['settings']['handler_settings']['view']['display_name'];
    $args = $this->handleArgs($this->field['settings']['handler_settings']['view']['args']);
    $result = array();
    if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
            $entities = $this->view->execute_display($display_name, $args);
      if (!empty($entities)) {
        $result = array_keys($entities);
      }
    }
    return $result;
  }
  
  public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
    $bundled_entities = $this->getReferencableEntities($input, '=', 6);
    $entities = array();
    foreach ($bundled_entities as $entities_list) {
      $entities += $entities_list;
    }
    if (empty($entities)) {
            form_error($element, t('No items found for %label', array('%label' => $element['#title'])));
    }
    elseif (count($entities) > 5) {
            form_error($element, t('Too many items found for %label. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
        '%label' => $element['#title'],
        '@value' => $input,
        '@id' => key($entities),
      )));
    }
    elseif (count($entities) > 1) {
            $multiples = array();
      foreach ($entities as $id => $name) {
        $multiples[] = filter_xss($name, array()) . ' (' . (int) $id . ')';
      }
      form_error($element, t('Multiple items found for %label: !multiple', array(
        '%label' => $element['#title'],
        '!multiple' => theme('item_list', array('items' => $multiples)),
      )));
    }
    else {
            return (int) key($entities);
    }
  }
  
  public function getLabel($entity) {
    return entity_label($this->field['settings']['target_type'], $entity);
  }
  
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
  }
  
  protected function handleArgs($args) {
        $data = array();
    $options = array('clear' => TRUE);
    if ($entity = $this->entity) {
                                    $info = entity_get_info($this->instance['entity_type']);
      if (!isset($entity->{$info['entity keys']['id']})) {
        $entity = clone $entity;
        $entity->{$info['entity keys']['id']} = '0';
        if (!empty($info['entity keys']['revision'])) {
          $entity->{$info['entity keys']['revision']} = '0';
        }
      }
      $data[$info['token type']] = $entity;
    }
        foreach ($args as $key => $arg) {
      $args[$key] = token_replace($arg, $data, $options);
    }
    return $args;
  }
}