<?php

/**
 * @file
 * Tests for media.module.
 */

/**
 * Defines base class for media test cases.
 */
class MediaWYSIWYGTestHelper extends DrupalWebTestCase {

  /**
   * Enable media and file entity modules for testing.
   */
  public function setUp() {
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    $modules[] = 'media_wysiwyg';
    parent::setUp($modules);
  }

  /**
    * Generates markup to be inserted for a file.
    *
    * This is a PHP version of InsertMedia.insert() from js/wysiwyg-media.js.
    *
    * @param int $fid
    *   Drupal file id
    * @param int $count
    *   Quantity of markup to insert
    * @param array $attributes
    *   Extra attributes to insert.
    * @param array $fields
    *   Extra field values to insert.
    *
    * @return string
    *   Filter markup.
    */
  protected function generateJsonTokenMarkup($fid, $count = 1, array $attributes = array(), array $fields = array()) {
    $markup = '';
    // Merge default atttributes.
    $attributes += array(
      'height' => 100,
      'width' => 100,
      'classes' => 'media-element file_preview',
    );

    // Build the data that is used in a media tag.
    $data = array(
      'fid' => $fid,
      'type' => 'media',
      'view_mode' => 'preview',
      'attributes' => $attributes,
      'fields' => $fields,
    );

    // Create the file usage markup.
    for ($i = 1; $i <= $count; $i++) {
      $markup .= '<p>[[' . drupal_json_encode($data) . ']]</p>';
    }

    return $markup;
  }

  /**
   * Utility function to create a test node.
   *
   * @param int $fid
   *   Create the node with media markup in the body field
    * @param array $attributes
    *   Extra attributes to insert to the file.
    * @param array $fields
    *   Extra field values to insert.
   *
   * @return int
   *   Returns the node id
   */
  protected function createNode($fid = FALSE, array $attributes = array(), array $fields = array()) {
    $markup = '';
    if (! empty($fid)) {
      $markup = $this->generateJsonTokenMarkup($fid, 1, $attributes, $fields);
    }

    // Create an article node with file markup in the body field.
    $edit = array(
      'title' => $this->randomName(8),
      'body[und][0][value]' => $markup,
    );
    // Save the article node. First argument is the URL, then the value array
    // and the third is the label the button that should be "clicked".
    $this->drupalPost('node/add/article', $edit, t('Save'));

    // Get the article node that was saved by the unique title.
    $node = $this->drupalGetNodeByTitle($edit['title']);
    return $node->nid;
  }

}
