<?php
// $Id:

/**
 * @file
 *
 * Provides the Feeds XPath Parser.
 */

/**
 * Takes a document and runs a user provided XPath query against it.
 */
class FeedsXPathParser extends FeedsParser {

  /**
   * Implementation of FeedsParser::parse().
   */
  public function parse(FeedsImportBatch $batch, FeedsSource $source) {
    $html = $batch->getRaw();

    $dom = new DOMDocument();
    @$dom->loadHTML($html);

    $xml = simplexml_import_dom($dom);

    $config = $source->getConfigFor($this);
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
    $results_ = array();

    foreach ($mappings as $mapping) {
      $source = $mapping['source'];
      $results_[$source] = $xml->xpath($config[$source]);
    }

    $results = array();
    foreach ($results_ as $source => $items) {
      foreach ($items as $key => $item) {
        if (isset($results[$key])) {
          $results[$key] = array_merge(array($source => $item), $results[$key]);
        }
        else {
          $results[$key] = array($source => $item);
        }
      }
    }

    $batch->setItems($results);
  }

  /**
   * Define defaults.
   */
  public function sourceDefaults() {
    return array('XPath' => '');
  }

  /**
   * Source form.
   */
  public function sourceForm($source_config) {
    $form = array();
    $form['#weight'] = -10;

    $mappings = feeds_importer($this->id)->processor->config['mappings'];
    $sources = $uniques = array();

    foreach ($mappings as $mapping) {
      $sources[] = $mapping['source'];
      if ($mapping['unique']) {
        $uniques[] = $mapping['source'];
      }
    }

    $items = array(
      t('Import scraped items with one or more of these entities: !columns.',
        array('!columns' => implode(', ', $sources))),
      format_plural(count($uniques),
        t('Entity <strong>!column</strong> is mandatory and considered unique: only one item per !column value will be created.',
          array('!column' => implode(', ', $uniques))),
        t('Entities <strong>!columns</strong> are mandatory and values in these columns are considered unique: only one entry per value in one of these columns will be created.',
          array('!columns' => implode(', ', $uniques)))),
    );
    $form['help']['#value'] = '<div class="help">'. theme('item_list', $items) .'</div>';

    foreach ($sources as $source) {
      $form[$source] = array(
        '#type'          => 'textfield',
        '#title'         => t('XPath for ' . $source),
        '#description'   => t('The XPath query to run.'),
        '#default_value' => isset($source_config[$source]) ? $source_config[$source] : '',
      );
    }
    return $form;
  }
}
