<?php

/**
 * @file
 * Tests for the token_actions module.
 */

class TokenActionsTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => t('Token action tests'),
      'description' => t('Test some of the token actions and tokens.'),
      'group' => t('Token'),
    );
  }

  function setUp() {
    parent::setUp('token', 'token_actions', 'trigger');
    $user = $this->drupalCreateUser(array('administer actions', 'administer site configuration', 'administer users'));
    $this->drupalLogin($user);
  }

  /**
   * Test user actions and triggers.
   */
  function testUserActions() {
    $insert_action = $this->createAction('token_actions_message_action', array(
      'message' => 'Yay [site-name] has a new user [user] with an ID of [uid] and e-mail address of [mail]!',
    ));
    $this->assignTriggerAction('user', 'insert', $insert_action);

    // Create a user to trigger the action.
    $edit = array();
    $edit['name'] = $this->randomName();
    $edit['mail'] = $edit['name'] .'@example.com';
    $edit['pass[pass1]'] = $this->randomName();
    $edit['pass[pass2]'] = $edit['pass[pass1]'];

    $this->drupalPost('admin/user/user/create', $edit, t('Create new account'));
    $account = user_load(array('name' => $edit['name']));
    $this->assertText("Yay Drupal has a new user {$account->name} with an ID of {$account->uid} and e-mail address of {$account->mail}!", 'Tokenized message displays');
  }

  /**
   * Create an action.
   *
   * @param $action
   *   The machine name of the action.
   * @param $edit
   *   An optional array to pass onto drupalPost() for configuring the action.
   *
   * @return
   *   The created action object.
   */
  function createAction($action, $edit = array()) {
    $edit += array(
      'actions_description' =>  $this->randomName(),
    );
    $this->drupalPost('admin/settings/actions/configure/'. md5($action), $edit, t('Save'));
    $this->assertText('The action has been successfully saved.');
    return db_fetch_object(db_query("SELECT * FROM {actions} WHERE type = 'system' AND callback = '%s' AND description = '%s'", $action, $edit['actions_description']));
  }

  /**
   * Assign an action to a trigger.
   *
   * @param $type
   *   The trigger type.
   * @param $trigger
   *   The trigger.
   * @param $action
   *   The action object.
   */
  function assignTriggerAction($type, $trigger, $action) {
    $edit['aid'] = md5($action->aid);
    $this->drupalPost("admin/build/trigger/{$type}", $edit, 'Assign', array(), array(), "trigger-{$type}-{$trigger}-assign-form");
    return $this->assertLinkByHref("admin/build/trigger/unassign/{$type}/{$trigger}/{$edit['aid']}", 0, t('Action assigned to @type @trigger trigger.', array('@type' => $type, '@trigger' => $trigger)));
  }
}
