<?php

/**
* Implementation of hook_rules_data_type_info().
*/
function emf_rules_data_type_info() {
  return array(
    'emf_list' => array(
      'label' => t('EMF list'),
      'class' => 'emf_list_rules_data_type',
      'identifiable' => FALSE,
      'uses_input_form' => TRUE,
      'eval input' => TRUE,
      'module' => 'EMF',
    ),
  );
}

/**
* Defines the rules emf list data type.
*/
class emf_list_rules_data_type extends rules_data_type {

  function get_default_input_form($info, $value) {
    $emf_lists = emf_db_get_lists();
    $list_options = array('' => '');
    foreach ($emf_lists as $list) {
      $list_options[$list->lid] = $list->name_api;
    }

    $info += array('required' => TRUE, 'description' => '');
    return array(
      '#type' => 'select',
      '#title' => $info['label'],
      '#description' => $info['description'],
      '#required' => $info['required'],
      '#default_value' => $value,
      '#options' => $list_options,
    );
  }
}

function emf_rules_action_info() {
  $actions = array();

  // add actions for each list
  $lists = emf_db_get_lists();

  foreach ($lists as $list) {
    $list_arguments = array(
      'list_id' => array(
        'type' => 'value',
        'default value' => $list->lid,
      ),
    );

    foreach ($list->field_mapping as $field) {
      $list_arguments[$field->key] = array(
        'label' => $field->name,
        'type' => 'string',
      );
    }

    $actions['emf_action_subscribe_to_list_' . $list->lid] = array(
      'label' => t('Subscribe to list: !list_name', array('!list_name' => $list->name_api)),
      'arguments' => $list_arguments,
      'module' => 'Email Marketing Framework',
      'base' => 'emf_action_subscribe_to_list',
      'set' => $list->lid,
    );
  }

  return $actions;
}

function emf_action_subscribe_to_list() {
  $args = func_get_args();

  $list_id = array_shift($args);

  $state = array_pop($args);
  $element = array_pop($args);
  $fields = array_pop($args);

  $mail = $fields['mail'];
  unset($fields['mail']);
  unset($fields['#eval input']);

  dsm($fields);

  require_once drupal_get_path('module', 'emf') .'/emf.db.inc';
  require_once drupal_get_path('module', 'emf') .'/emf.helpers.inc';

  //dsm($settings);

  emf_helpers_subscribe($mail, $list_id, $fields);
}