<?php

/**
 * @file
 * Tests for the Skinr UI module.
 */

/**
 * Base class for Skinr UI tests.
 */
class SkinrUITestCase extends DrupalWebTestCase {
  protected $profile = 'testing';

  function setUp() {
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    parent::setUp(array_merge(array('block', 'comment', 'contextual', 'skinr_ui', 'skinr_ui_test'), $modules));

    $this->admin_user = $this->drupalCreateUser(array(
      'administer blocks',
      'access contextual links',
      'administer skinr',
      'edit skin settings',
      'edit advanced skin settings',
    ));
    $this->drupalLogin($this->admin_user);

    // Enable main system block for content region and the user menu block for
    // the first sidebar.
    // @see http://drupal.org/node/913086
    $default_theme = variable_get('theme_default', 'bartik');
    db_merge('block')
      ->key(array(
        'theme' => $default_theme,
        'module' => 'system',
        'delta' => 'main',
      ))
      ->fields(array(
        'status' => 1,
        'region' => 'content',
        'pages' => '',
      ))
      ->execute();
    db_merge('block')
      ->key(array(
        'theme' => $default_theme,
        'module' => 'system',
        'delta' => 'user-menu',
      ))
      ->fields(array(
        'status' => 1,
        'region' => 'sidebar_first',
        'pages' => '',
      ))
      ->execute();
    db_merge('block')
      ->key(array(
        'theme' => $default_theme,
        'module' => 'search',
        'delta' => 'form',
      ))
      ->fields(array(
        'status' => 1,
        'region' => 'sidebar_first',
        'pages' => '',
      ))
      ->execute();
  }

  /**
   * Asserts that a class is set for the given element id.
   *
   * @param $id
   *   Id of the HTML element to check.
   * @param $class
   *   The class name to check for.
   * @param $message
   *   Message to display.
   * @return
   *   TRUE on pass, FALSE on fail.
   */
  function assertSkinrClass($id, $class, $message = '') {
    $elements = $this->xpath('//div[@id=:id]', array(':id' => $id));
    $class_attr = (string) $elements[0]['class'];
    $this->assertTrue(strpos($class_attr, ' ' . $class . ' '), $message);
  }

  /**
   * Asserts that a class is not set for the given element id.
   *
   * @param $id
   *   Id of the HTML element to check.
   * @param $class
   *   The class name to check for.
   * @param $message
   *   Message to display.
   * @return
   *   TRUE on pass, FALSE on fail.
   */
  function assertNoSkinrClass($id, $class, $message = '') {
    $elements = $this->xpath('//div[@id=:id]', array(':id' => $id));
    $class_attr = (string) $elements[0]['class'];
    $this->assertFalse(strpos($class_attr, ' ' . $class . ' '), $message);
  }
}

/**
 * Tests UI functionality.
 */
class SkinrUIBasicTestCase extends SkinrUITestCase {
  public static function getInfo() {
    return array(
      'name' => 'UI',
      'description' => 'Tests basic Skinr UI functionality.',
      'group' => 'Skinr',
    );
  }

  /**
   * Tests basic configuration and applying of a skin.
   *
   * @todo For some reason, contextual links are not visible in the debug output
   *   when running tests; likely a core bug in contextual.js. However, the
   *   links are contained in the output. Keep this in mind when manually
   *   reviewing the debug output after running tests!
   * @todo Remove the overly verbose inline comments after the Skinr development
   *   team has figured out how to write tests.
   */
  function testSkinEdit() {
    // Go to the front page, on which the user menu block should appear.
    $this->drupalGet('');
    // Click the first (index 0) 'Edit skin' link on the page, which should be
    // the link in the contextual links of the user menu block, since no other
    // skinnable elements are visible on the page.
    // For now, this is a simple way to assert and access Skinr links. In the
    // future, we want to be more explicit in testing; i.e., verify that there
    // is really only this link, its 'href' is correct, that it appears in the
    // right location, etc.pp; DrupalWebTestCase ($this) provides many helper
    // functions to assert such things.
    $this->clickLink(t('Edit skin'), 0);
    // Verify that we end up on the expected URL to configure skins for the
    // user menu block.
    $front = variable_get('site_frontpage', 'node');
    $this->assertUrl('admin/structure/skinr/edit/block/system__user-menu/configure', array(
      'query' => array('destination' => $front),
    ));

    // skinr_ui_test.module got enabled in setUp(), so its skins should be
    // available.
    // Verify that we can apply the skinr_ui_test_border skin to the block.
    $edit = array(
      'skinr_settings[bartik][groups][general][skinr_ui_test_bgcolor]' => 'bgcolor_red',
    );
    // NULL means that we want to post to the page that is still contained in
    // SimpleTest's internal browser; i.e., the page of the path above. Instead
    // of passing NULL, you can also pass a Drupal system path and SimpleTest
    // will automatically do a $this->drupalGet($path) for you before posting.
    $this->drupalPost(NULL, $edit, t('Save'));

    // After posting, we expect to be redirected to the originating page, due
    // to the 'destination' query parameter in the 'Edit skin' link. Since we
    // came from the front page, Drupal will redirect us to the actual path of
    // the front page, not ''.
    // Verify that we were redirected to the originating page.
    $this->assertUrl($front);

    // Verify that the skin has been applied.
    $this->assertSkinrClass('block-system-user-menu', 'bgcolor-red', 'CSS class of configured skin option found.');
  }

  /**
   * Tests access control for editing additional CSS classes.
   */
  function testSkinAdditionalEdit() {
    // Verify that we can apply additional CSS classes.
    $edit = array(
      'skinr_settings[bartik][groups][_additional][_additional]' => 'additional',
    );
    $this->drupalPost('admin/structure/skinr/edit/block/system__user-menu/configure', $edit, t('Save'));

    // Verify that the skin has been applied.
    $this->drupalGet('');
    $this->assertSkinrClass('block-system-user-menu', 'additional', 'Additional CSS class <em>additional</em> of configured skin option found.');

    // Now let's check the same for a user that has no access to alter this.
    $user = $this->drupalCreateUser(array('edit skin settings'));
    $this->drupalLogin($user);

    // Verify that the additional CSS classes field is not enabled.
    $this->drupalGet('admin/structure/skinr/edit/block/system__user-menu/configure');
    $this->assertNoFieldByName('skinr_settings[bartik][groups][_additional][_additional]', NULL, 'Additional CSS classes field is not enabled for this user.');

    // Save form when additional CSS classes is not set.
    $edit = array();
    $this->drupalPost(NULL, $edit, t('Save'));

    // Verify that the old class is still applied.
    $this->drupalGet('');
    $this->assertSkinrClass('block-system-user-menu', 'additional', 'Additional CSS class <em>additional</em> of configured skin option found.');
  }

  /**
   * Tests output of widgets on the skin configuration form.
   */
  function testSkinEditWidgets() {
    // Go to the edit page for system__user_menu block.
    $this->drupalGet('admin/structure/skinr/library');
    $this->drupalGet('admin/structure/skinr/edit/block/system__user-menu/configure');

    // Check the widgets.
    $this->assertFieldByName('skinr_settings[bartik][groups][general][skinr_ui_test_bgcolor]', NULL, 'Widget with valid type is displayed.');
    $this->assertNoFieldByName('skinr_settings[bartik][groups][box][skinr_ui_test_border]', NULL, 'Widget with invalid type is not displayed.');
    $this->assertFieldByName('skinr_settings[bartik][groups][general][skinr_ui_test_custom][custom]', NULL, 'Widget with form callback is displayed.');

    // Check for output from empty groups.
    $this->assertNoRaw('id="edit-skinr-settings-block-group-bartik-box"', 'Resulting empty group is not displayed.');
  }

  /**
   * Tests access control for editing additional CSS classes.
   */
  function testSkinEditThemeHooks() {
    // Widget should appear for system blocks.
    $this->drupalGet('admin/structure/skinr/edit/block/system__user-menu/configure');
    $this->assertField('edit-skinr-settings-bartik-groups-general-skinr-ui-test-color-color-white', 'The widget, which is limited to system blocks, appeared on the configuration form for system\'s user-menu block.');

    // Widget should not appear search blocks.
    $this->drupalGet('admin/structure/skinr/edit/block/search__form/configure');
    $this->assertNoField('edit-skinr-settings-bartik-groups-general-skinr-ui-test-color-color-white', 'The widget, which is limited to system blocks, did not appear on the configuration form for search\'s form block.');


    // Widget should appear for page node comments.
    $this->drupalGet('admin/structure/skinr/edit/comment/page/configure');
    $this->assertField('edit-skinr-settings-bartik-groups-general-skinr-ui-test-color-color-white', 'The widget, which is limited to page node comments, appeared on the configuration form for page node comments.');

    // Widget should not appear for article node comments.
    $this->drupalGet('admin/structure/skinr/edit/comment/article/configure');
    $this->assertNoField('edit-skinr-settings-bartik-groups-general-skinr-ui-test-color-color-white', 'The widget, which is limited to page node comments, did not appear on the configuration form for article node comments.');


    // Widget should appear for page nodes.
    $this->drupalGet('admin/structure/skinr/edit/node/page/configure');
    $this->assertField('edit-skinr-settings-bartik-groups-general-skinr-ui-test-color-color-white', 'The widget, which is limited to page node types, appeared on the configuration form for page node types.');

    // Widget should not appear for article nodes.
    $this->drupalGet('admin/structure/skinr/edit/node/article/configure');
    $this->assertNoField('edit-skinr-settings-bartik-groups-general-skinr-ui-test-color-color-white', 'The widget, which is limited to page node types, did not appear on the configuration form for article node types.');
  }
}

/**
 * Tests administrative pages functionality.
 */
class SkinrUIAdminTestCase extends SkinrUITestCase {
  public static function getInfo() {
    return array(
      'name' => 'Administration',
      'description' => 'Tests administrative Skinr UI functionality.',
      'group' => 'Skinr',
    );
  }

  function setUp() {
    parent::setUp(array('skinr_test'));

    $this->admin_user = $this->drupalCreateUser(array(
      'administer skinr',
      'edit skin settings',
      'edit advanced skin settings',
    ));
    $this->drupalLogin($this->admin_user);

    // Enable Garland and skinr_test_subtheme without enabling its base theme in
    // order to test subtheme inheritance functionality.
    theme_enable(array('garland', 'skinr_test_subtheme'));
  }

  /**
   * Tests default status of skins.
   *
   * The skinr_test_basetheme skin defined by the skinr_test_basetheme theme
   * specifies a default status for itself. Its subtheme should inherit the
   * status of the basetheme.
   *
   * @todo Add assertions for 'default status' itself.
   */
  function testSkinDefaultStatus() {
    // Verify that it is enabled for the skinr_test_subtheme.
    $this->drupalGet('admin/structure/skinr/library/list/skinr_test_subtheme');
    $this->assertFieldChecked('edit-skins-general-skinr-test-basetheme-enable', 'skinr_test_basetheme skin is enabled for skinr_test_subtheme.');

    // Verify that it is disabled for Bartik by default.
    $this->drupalGet('admin/structure/skinr/library/list/bartik');
    $this->assertNoFieldChecked('edit-skins-general-skinr-test-basetheme-enable', 'skinr_test_basetheme skin is disabled for Bartik.');

    // Verify that it is disabled for Garland by default.
    $this->drupalGet('admin/structure/skinr/library/list/garland');
    $this->assertNoFieldChecked('edit-skins-general-skinr-test-basetheme-enable', 'skinr_test_basetheme skin is disabled for Garland.');

    // Override the status for skinr_test_subtheme and Bartik, then verify them.
    $skin = (object) array(
      'theme' => 'skinr_test_subtheme',
      'module' => 'block',
      'element' => 'system__user-menu',
      'skin' => 'skinr_test_subtheme',
      'options' => array('option1', 'option2'),
      'status' => 1,
    );
    skinr_skin_save($skin);
    $skin = skinr_skin_load($skin->sid);

    // Override the default skin.
    $skin->element = 'system-main';
    $this->drupalGet('admin/structure/skinr');
    $this->clickLink(t('disable'), 0);
    // Unaltered skin configuration object should have been saved with only the status updated.
    // Load an uncached version of the skin configuration object.
    $skin = skinr_skin_load_unchanged($skin->sid);
    $this->assertFalse($skin->status, 'Status was disabled successfully.');
    $this->assertEqual($skin->element, 'system__user-menu', 'Only status was updated, even though the object was modified before updating status.');

    // Enable the skin configuration.
    $this->drupalGet('admin/structure/skinr');
    $this->clickLink(t('enable'), 0);
    // Load an uncached version of the skin configuration object.
    $skin = skinr_skin_load_unchanged($skin->sid);
    $this->assertTrue($skin->status, 'Status was enabled successfully.');
  }

  /**
   * Tests skin group functionality.
   */
  function testSkinGroups() {
    $this->drupalGet('admin/structure/skinr/library');

    // Verify that the 'General' (default) group appears.
    $this->assertText(t('General'));

    // Verify that the 'Box styles' group appears, since skinr_ui_test module
    // registers a skin in that group.
    $this->assertText(t('Box styles'));
  }

  /**
   * Tests skin configuration listing functionality.
   */
  function testSkinListing() {
    $skin = (object) array(
      'theme' => 'skinr_test_subtheme',
      'module' => 'block',
      'element' => 'system__user-menu',
      'skin' => 'skinr_test_subtheme',
      'options' => array('option1', 'option2'),
      'status' => 1,
    );
    skinr_skin_save($skin);

    // Verify that the skin configuration appears on the skin configurations overview page.
    $this->drupalGet('admin/structure/skinr');
    $this->assertLinkByHref('admin/structure/skinr/skin/' . $skin->sid . '/delete', 0, 'Skin configuration was found on overview page.');

    // @todo Should we check the filtering and update options functionality?
  }
}

/**
 * Tests UI functionality for Block plugin.
 */
class SkinrUIPluginTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Plugins UI - Core',
      'description' => 'Tests Skinr UI functionality for functionality plugins from Drupal core.',
      'group' => 'Skinr',
    );
  }

  function setUp() {
    parent::setUp(array('block', 'comment', 'node', 'skinr_ui', 'skinr_test'));

    $this->admin_user = $this->drupalCreateUser(array(
      'administer blocks',
      'access comments',
      'access content',
      'post comments',
      'skip comment approval',

      'access contextual links',
      'administer skinr',
      'edit skin settings',
      'edit advanced skin settings',
      'bypass node access',
    ));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Asserts that a select option in the current page exists.
   *
   * @param $name
   *   Id of select field to assert.
   * @param $option
   *   Option to assert.
   * @param $message
   *   Message to display.
   * @return
   *   TRUE on pass, FALSE on fail.
   */
  protected function assertOptionExists($name, $option, $message = '') {
    $elements = $this->xpath('//select[@name=:name]//option[@value=:option]', array(':name' => $name, ':option' => $option));
    return $this->assertTrue(isset($elements[0]), $message ? $message : t('Option @option for field @name exists.', array('@option' => $option, '@name' => $name)), t('Browser'));
  }

  /**
   * Tests block plugin.
   */
  function testBlock() {
    // Enable user menu block for the first sidebar.
    // @see http://drupal.org/node/913086
    $default_theme = variable_get('theme_default', 'bartik');
    db_merge('block')
      ->key(array(
        'theme' => $default_theme,
        'module' => 'system',
        'delta' => 'user-menu',
      ))
      ->fields(array(
        'status' => 1,
        'region' => 'sidebar_first',
        'pages' => '',
      ))
      ->execute();

    // Get front page.
    $this->drupalGet('');

    // Make sure our contextual link appears on the page.
    $this->assertLinkByHref('admin/structure/skinr/edit/block/system__user-menu/configure', 0, 'Contexual link to edit block\'s skin configuration was found.');

    // Make sure this block's options are returned.
    $this->drupalGet('admin/structure/skinr/add');
    $this->assertOptionExists('element', 'system__user-menu', 'User menu block was returned by block_skinr_ui_element_options().');

    // Test the returned element title.
    $skin = (object) array(
      'theme' => $default_theme,
      'module' => 'block',
      'element' => 'system__user-menu',
      'skin' => 'skinr_ui_test_bgcolor',
      'options' => array('bgcolor_red'),
      'status' => 1,
    );
    skinr_skin_save($skin);

    $title = reset(skinr_invoke_all('skinr_ui_element_title', $skin->module, $skin->element, $skin->theme));
    $this->assertTrue($title == 'User menu', 'Block title was returned.');
  }

  /**
   * Tests comment plugin.
   */
  function testComment() {
    $default_theme = variable_get('theme_default', 'bartik');

    // Create a node.
    $node1 = $this->drupalCreateNode(array('type' => 'article'));

    // Go to node.
    $uri = entity_uri('node', $node1);
    $this->drupalGet($uri['path']);

    // Add a comment to the node. With bartik the contextual links won't
    // display until there is at least one comment.
    $edit = array(
      'comment_body[und][0][value]' => $this->randomString(128),
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    // Make sure our contextual link appears on the page.
    $this->assertLinkByHref('admin/structure/skinr/edit/comment/article/configure', 0, 'Contexual link to edit comment\'s skin configuration was found.');

    // Make sure this block's options are returned.
    $this->drupalGet('admin/structure/skinr/add');
    $this->assertOptionExists('element', 'article', 'Node type was returned by node_skinr_ui_element_options().');

    // Test the returned element title.
    $skin = (object) array(
      'theme' => $default_theme,
      'module' => 'comment',
      'element' => 'article',
      'skin' => 'skinr_ui_test_bgcolor',
      'options' => array('bgcolor_red'),
      'status' => 1,
    );
    skinr_skin_save($skin);

    $title = reset(skinr_invoke_all('skinr_ui_element_title', $skin->module, $skin->element, $skin->theme));
    $this->assertEqual($title, 'Article', 'Node type title was returned.');
  }

  /**
   * Tests node plugin.
   */
  function testNode() {
    $default_theme = variable_get('theme_default', 'bartik');

    // Create a node.
    $node = $this->drupalCreateNode(array('type' => 'article'));

    // Go to node.
    $uri = entity_uri('node', $node);
    $this->drupalGet($uri['path']);

    // Make sure our contextual link appears on the page.
    $this->assertLinkByHref('admin/structure/skinr/edit/node/article/configure', 0, 'Contexual link to edit node\'s skin configuration was found.');

    // Make sure this block's options are returned.
    $this->drupalGet('admin/structure/skinr/add');
    $this->assertOptionExists('element', 'article', 'Node type was returned by node_skinr_ui_element_options().');

    // Test the returned element title.
    $skin = (object) array(
      'theme' => $default_theme,
      'module' => 'node',
      'element' => 'article',
      'skin' => 'skinr_ui_test_bgcolor',
      'options' => array('bgcolor_red'),
      'status' => 1,
    );
    skinr_skin_save($skin);

    $title = reset(skinr_invoke_all('skinr_ui_element_title', $skin->module, $skin->element, $skin->theme));
    $this->assertEqual($title, 'Article', 'Node type title was returned.');
  }

  /**
   * Tests node plugin.
   */
  function testSystem() {
    // @todo Add tests for html and region hooks.
  }
}

/**
 * Tests UI functionality for Block plugin.
 */
/**
 * Tests UI functionality for Block plugin.
 */
class SkinrUIPluginViewsTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Plugins UI - Views',
      'description' => 'Tests Skinr UI functionality for functionality plugin from Views.',
      'dependencies' => array('views', 'views_ui'),
      'group' => 'Skinr',
    );
  }

  function setUp() {
    parent::setUp(array('views_ui', 'skinr_ui_test'));

    $this->admin_user = $this->drupalCreateUser(array(
      'administer views',
      'access all views',

      'access contextual links',
      'administer skinr',
      'edit skin settings',
      'edit advanced skin settings',
    ));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Asserts that a select option in the current page exists.
   *
   * @param $name
   *   Id of select field to assert.
   * @param $option
   *   Option to assert.
   * @param $message
   *   Message to display.
   * @return
   *   TRUE on pass, FALSE on fail.
   */
  protected function assertOptionExists($name, $option, $message = '') {
    $elements = $this->xpath('//select[@name=:name]//option[@value=:option]', array(':name' => $name, ':option' => $option));
    return $this->assertTrue(isset($elements[0]), $message ? $message : t('Option @option for field @name exists.', array('@option' => $option, '@name' => $name)), t('Browser'));
  }

  /**
   * Tests views plugin.
   */
  function testViews() {
    $default_theme = variable_get('theme_default', 'bartik');

    // Go to the view's page.
    $this->drupalGet('skinr-ui-test-view');

    // Make sure our contextual link appears on the page.
    $this->assertLinkByHref('admin/structure/skinr/edit/views/skinr_ui_test__page/configure', 0, "Contexual link to edit view's skin configuration was found.");

    // Make sure this view's options are returned.
    $this->drupalGet('admin/structure/skinr/add');
    $this->assertOptionExists('element', 'skinr_ui_test__default', 'Default display for our view was returned by views_skinr_ui_element_options().');
    $this->assertOptionExists('element', 'skinr_ui_test__page', 'Page display for our view was returned by views_skinr_ui_element_options().');

    // Test the returned element title.
    $skin = (object) array(
      'theme' => $default_theme,
      'module' => 'views',
      'element' => 'skinr_ui_test__page',
      'skin' => 'skinr_ui_test_bgcolor',
      'options' => array('bgcolor_red'),
      'status' => 1,
    );
    skinr_skin_save($skin);

    $title = reset(skinr_invoke_all('skinr_ui_element_title', $skin->module, $skin->element, $skin->theme));
    $this->assertEqual($title, 'Skinr UI Test', 'View title was returned.');
  }
}
