<?php

/**
 * @file
 * Test cases file.
 */

/**
 * Class for testing Draggableviews module.
 */
class DraggableviewsTestCase extends DrupalWebTestCase {

  function setUp() {
    parent::setUp(array('ctools', 'views', 'views_ui', 'entity', 'draggableviews', 'draggableviews_test'));
  }

  /**
   * Fork from drupalPost().
   *
   * When action of the form determined we don't care about exposed filter
   * arguments passed to the view. In this fork we use
   * $this->getUrl() unconditionally.
   */
  protected function drupalDraggableviewsPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
    $submit_matches = FALSE;
    $ajax = is_array($submit);
    if (isset($path)) {
      $this->drupalGet($path, $options);
    }
    if ($this->parse()) {
      $edit_save = $edit;
      // Let's iterate over all the forms.
      $xpath = "//form";
      if (!empty($form_html_id)) {
        $xpath .= "[@id='" . $form_html_id . "']";
      }
      $forms = $this->xpath($xpath);
      foreach ($forms as $form) {
        // We try to set the fields of this form as specified in $edit.
        $edit = $edit_save;
        $post = array();
        $upload = array();
        $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
//        $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
        $action = $this->getUrl();
        if ($ajax) {
          $action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
          // Ajax callbacks verify the triggering element if necessary, so while
          // we may eventually want extra code that verifies it in the
          // handleForm() function, it's not currently a requirement.
          $submit_matches = TRUE;
        }

        // We post only if we managed to handle every field in edit and the
        // submit button matches.
        if (!$edit && ($submit_matches || !isset($submit))) {
          $post_array = $post;
          if ($upload) {
            // TODO: cURL handles file uploads for us, but the implementation
            // is broken. This is a less than elegant workaround. Alternatives
            // are being explored at #253506.
            foreach ($upload as $key => $file) {
              $file = drupal_realpath($file);
              if ($file && is_file($file)) {
                $post[$key] = '@' . $file;
              }
            }
          }
          else {
            foreach ($post as $key => $value) {
              // Encode according to application/x-www-form-urlencoded
              // Both names and values needs to be urlencoded, according to
              // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
              $post[$key] = urlencode($key) . '=' . urlencode($value);
            }
            $post = implode('&', $post) . $extra_post;
          }
          $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
          // Ensure that any changes to variables in the other thread are picked up.
          $this->refreshVariables();

          // Replace original page output with new output from redirected page(s).
          if ($new = $this->checkForMetaRefresh()) {
            $out = $new;
          }
          $this->verbose('POST request to: ' . $path .
                         '<hr />Ending URL: ' . $this->getUrl() .
                         '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
                         '<hr />' . $out);
          return $out;
        }
      }
      // We have not found a form which contained all fields of $edit.
      foreach ($edit as $name => $value) {
        $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
      }
      if (!$ajax && isset($submit)) {
        $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
      }
      $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
    }
  }
}

/**
 * Testing Native Handler.
 */
class DraggableviewsNativeHandlerTestCase extends DraggableviewsTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Native handler',
      'description' => 'Test the native handler.',
      'group' => 'Draggableviews',
    );
  }

  function testSort() {
    $permissions = array('access content');
    $rid = $this->drupalCreateRole($permissions);

    // Create five test users.
    $accounts = array();
    for ($i = 0; $i < 5; $i++) {
      $edit = array();
      $edit['name']   = $this->randomName();
      // First three users should be prefixed 'test_'.
      if ($i < 3) {
        $edit['name'] = 'test_' . $edit['name'];
      }
      $edit['mail']   = $edit['name'] . '@example.com';
      $edit['roles']  = array($rid => $rid);
      $edit['pass']   = user_password();
      $edit['status'] = 1;

      $account = user_save(drupal_anonymous_user(), $edit);
      $account->pass_raw = $edit['pass'];

      $accounts[$account->uid] = $account;
    }

    $account = $this->drupalCreateUser(array('access content', 'access draggableviews', 'access user profiles', 'access contextual links'));
    $this->drupalLogin($account);

    // Now lets sort and save a view.
    $edit = array(
      'draggableviews[0][weight]' => 0,
      'draggableviews[0][id]' => 1,
      'draggableviews[1][weight]' => 1,
      'draggableviews[1][id]' => 2,
      'draggableviews[2][weight]' => 2,
      'draggableviews[2][id]' => 3,
      'draggableviews[3][weight]' => 3,
      'draggableviews[3][id]' => 4,
      'draggableviews[4][weight]' => 4,
      'draggableviews[4][id]' => 5,
      'draggableviews[5][weight]' => 5,
      'draggableviews[5][id]' => 6,
      'draggableviews[6][weight]' => 6,
      'draggableviews[6][id]' => 7,
    );
    $this->drupalPost('users-set', $edit, t('Save'));

    // Assert that first user is on first place, and second is on second.
    $first_row = $this->xpath('//tr[@class="odd views-row-first draggable"]/td/a[@class="username"]');
    $second_row = $this->xpath('//tr[@class="even draggable"]/td/a[@class="username"]');
    $this->assertEqual((string) $first_row[0], 'placeholder-for...', t('First row user uid 1.'));
    $this->assertEqual((string) $second_row[0], $accounts[2]->name, t('Second row user uid 2.'));

    // Now save a different sort (first and second rows changed places).
    $edit = array(
      'draggableviews[0][weight]' => 0,
      'draggableviews[0][id]' => 2,
      'draggableviews[1][weight]' => 1,
      'draggableviews[1][id]' => 1,
      'draggableviews[2][weight]' => 2,
      'draggableviews[2][id]' => 3,
      'draggableviews[3][weight]' => 3,
      'draggableviews[3][id]' => 4,
      'draggableviews[4][weight]' => 4,
      'draggableviews[4][id]' => 5,
      'draggableviews[5][weight]' => 5,
      'draggableviews[5][id]' => 6,
      'draggableviews[6][weight]' => 6,
      'draggableviews[6][id]' => 7,
    );
    $this->drupalPost('users-set', $edit, t('Save'));
    // Assert that first user is on second place, and second user is on first.
    $first_row = $this->xpath('//tr[@class="odd views-row-first draggable"]/td/a[@class="username"]');
    $second_row = $this->xpath('//tr[@class="even draggable"]/td/a[@class="username"]');
    $this->assertEqual((string) $first_row[0], $accounts[2]->name, t('First row user uid 2.'));
    $this->assertEqual((string) $second_row[0], 'placeholder-for...', t('Second row user uid 1.'));

    // Apply exposed filter and set weights.
    $edit = array(
      'draggableviews[0][weight]' => 0,
      'draggableviews[0][id]' => 4,
      'draggableviews[1][weight]' => 1,
      'draggableviews[1][id]' => 3,
      'draggableviews[2][weight]' => 2,
      'draggableviews[2][id]' => 2,
    );
    $this->drupalDraggableviewsPost('users-set', $edit, t('Save'), array('query' => array('mail' => 'test')));

    // Now lets check display view page.
    $this->drupalGet('users-display');
    $first_row = $this->xpath('//tr[@class="odd views-row-first"]/td/a[@class="username"]');
    $second_row = $this->xpath('//tr[@class="even"]/td/a[@class="username"]');
    $this->assertEqual((string) $first_row[0], $accounts[2]->name, t('Display view. First row user uid 2.'));
    $this->assertEqual((string) $second_row[0], 'placeholder-for...', t('Display view. Second row user uid 1.'));

    // Check display view with applied exposed filter.
    $this->drupalGet('users-display', array('query' => array('mail' => 'test')));
    $first_row = $this->xpath('//tr[@class="odd views-row-first"]/td/a[@class="username"]');
    $second_row = $this->xpath('//tr[@class="even"]/td/a[@class="username"]');
    $this->assertEqual((string) $first_row[0], $accounts[4]->name, t('Display view. Exposed filter applied. First row user uid 4.'));
    $this->assertEqual((string) $second_row[0], $accounts[3]->name, t('Display view. Exposed filter applied. Second row user uid 3.'));

    // Check contextual link existence.
    $contextual_links = $this->xpath('//ul[@class="contextual-links views-contextual-links-page"]/li/a');
    $href = (string) $contextual_links[0]['href'];
    $this->assertTrue(strpos($href, 'users-set?destination=users-display') !== FALSE, t('Contextual link exists.'));
  }
}

/**
 * Testing Field API Handler.
 */
class DraggableviewsFieldAPIHandlerTestCase extends DraggableviewsTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Field API handler',
      'description' => 'Test the Field API handler.',
      'group' => 'Draggableviews',
    );
  }

  public function testSort() {
    $this->createField();

    $account = $this->drupalCreateUser(array('access content', 'access draggableviews', 'access user profiles', 'access contextual links'));
    $this->drupalLogin($account);

    // Create five nodes.
    $nodes = array();
    for ($i = 0; $i < 5; $i++) {
      $node = $this->drupalCreateNode(array('type' => 'article'));
      $nodes[$node->nid] = $node;
    }

    // Now lets sort and save a view.
    $edit = array(
      'draggableviews[0][weight]' => 0,
      'draggableviews[0][id]' => 1,
      'draggableviews[1][weight]' => 1,
      'draggableviews[1][id]' => 2,
      'draggableviews[2][weight]' => 2,
      'draggableviews[2][id]' => 3,
      'draggableviews[3][weight]' => 3,
      'draggableviews[3][id]' => 4,
      'draggableviews[4][weight]' => 4,
      'draggableviews[4][id]' => 5,
    );
    $this->drupalPost('nodes-set', $edit, t('Save'));
    // Assert that first node is on first place, and second is on second.
    $first_row = $this->xpath('//tr[@class="odd views-row-first draggable"]/td/a');
    $second_row = $this->xpath('//tr[@class="even draggable"]/td/a');
    $this->assertEqual((string) $first_row[0], $nodes[1]->title, t('First row node nid 1.'));
    $this->assertEqual((string) $second_row[0], $nodes[2]->title, t('Second row node nid 2.'));

    // Now save a different sort (first and second rows changed places).
    $edit = array(
      'draggableviews[0][weight]' => 0,
      'draggableviews[0][id]' => 2,
      'draggableviews[1][weight]' => 1,
      'draggableviews[1][id]' => 1,
      'draggableviews[2][weight]' => 2,
      'draggableviews[2][id]' => 3,
      'draggableviews[3][weight]' => 3,
      'draggableviews[3][id]' => 4,
      'draggableviews[4][weight]' => 4,
      'draggableviews[4][id]' => 5,
    );
    $this->drupalPost('nodes-set', $edit, t('Save'));
    // Assert that first node is on second place, and second is on first.
    $first_row = $this->xpath('//tr[@class="odd views-row-first draggable"]/td/a');
    $second_row = $this->xpath('//tr[@class="even draggable"]/td/a');
    $this->assertEqual((string) $first_row[0], $nodes[2]->title, t('First row node nid 2.'));
    $this->assertEqual((string) $second_row[0], $nodes[1]->title, t('Second row node nid 1.'));

    // Check display view order.
    $this->drupalGet('nodes-display');
    $first_row = $this->xpath('//tr[@class="odd views-row-first"]/td/a');
    $second_row = $this->xpath('//tr[@class="even"]/td/a');
    $this->assertEqual((string) $first_row[0], $nodes[2]->title, t('First row node nid 2.'));
    $this->assertEqual((string) $second_row[0], $nodes[1]->title, t('Second row node nid 1.'));

    // Check values of nodes.
    $node1 = node_load(1);
    $node2 = node_load(2);
    $this->assertTrue($node1->field_weight[LANGUAGE_NONE][0]['value'] > $node2->field_weight[LANGUAGE_NONE][0]['value'], t('Weight of node 1 is more than weight of node 2.'));
  }

  // Create a integer field for Article nodes.
  function createField() {
    $field = array(
      'translatable' => '0',
      'entity_types' => array(),
      'settings' => array(),
      'storage' => array(
        'type' => 'field_sql_storage',
        'settings' => array(),
        'module' => 'field_sql_storage',
        'active' => '1',
        'details' => array(
          'sql' => array(
            'FIELD_LOAD_CURRENT' => array(
              'field_data_field_weight' => array(
                'value' => 'field_weight_value',
              ),
            ),
            'FIELD_LOAD_REVISION' => array(
              'field_revision_field_weight' => array(
                'value' => 'field_weight_value',
              ),
            ),
          ),
        ),
      ),
      'foreign keys' => array(),
      'indexes' => array(),
      'id' => '5',
      'field_name' => 'field_weight',
      'type' => 'number_integer',
      'module' => 'number',
      'active' => '1',
      'locked' => '0',
      'cardinality' => '1',
      'deleted' => '0',
      'columns' => array(
        'value' => array(
          'type' => 'int',
          'not null' => FALSE,
        ),
      ),
      'bundles' => array(
        'node' => array(
          0 => 'article',
        ),
      ),
    );
    field_create_field($field);

    $instance = array(
      'label' => 'Weight',
      'widget' => array(
        'weight' => 0,
        'type' => 'number',
        'module' => 'number',
        'active' => 0,
        'settings' => array(),
      ),
      'settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
        'user_register_form' => FALSE,
      ),
      'display' => array(
        'default' => array(
          'label' => 'above',
          'type' => 'number_integer',
          'settings' => array(
            'thousand_separator' => ' ',
            'decimal_separator' => '.',
            'scale' => 0,
            'prefix_suffix' => TRUE,
          ),
          'module' => 'number',
          'weight' => 11,
        ),
      ),
      'required' => 0,
      'description' => '',
      'default_value' => NULL,
      'id' => '7',
      'field_id' => '5',
      'field_name' => 'field_weight',
      'entity_type' => 'node',
      'bundle' => 'article',
      'deleted' => '0',
    );
    field_create_instance($instance);
  }
}
