<?php
// $Id: bulk_export.module,v 1.3.2.2 2010/07/16 20:38:01 merlinofchaos Exp $

/**
 * @file
 * Perform bulk exports.
 */

/**
 * Implementation of hook_perm().
 */
function bulk_export_perm() {
  return array('use bulk exporter');
}

/**
 * Implementation of hook_theme().
 */
function bulk_export_theme() {
  return array('bulk_export_export_form' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

/**
 * Implementation of hook_menu().
 */
function bulk_export_menu() {
  $items['admin/build/bulkexport'] = array(
    'title' => 'Bulk Exporter',
    'description' => 'Bulk-export multiple CTools-handled data objects to code.',
    'access arguments' => array('use bulk exporter'),
    'page callback' => 'bulk_export_export',
  );
  $items['admin/build/bulkexport/results'] = array(
    'access arguments' => array('use bulk exporter'),
    'page callback' => 'bulk_export_export',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * FAPI gateway to the bulk exporter.
 */
function bulk_export_export() {
  ctools_include('export');
  $schemas = ctools_export_get_schemas(TRUE);
  $exportables = $export_tables = array();

  foreach ($schemas as $table => $schema) {
    if (!empty($schema['export']['list callback']) && function_exists($schema['export']['list callback'])) {
      $exportables[$table] = $schema['export']['list callback']();
    }
    else {
      $exportables[$table] = ctools_export_default_list($table, $schema);
    }
    natcasesort($exportables[$table]);
    $export_tables[$table] = $schema['module'];
  }
  if ($exportables) {
    ctools_include('form');
    $form_state = array(
      're_render' => FALSE,
      'no_redirect' => TRUE,
      'exportables' => $exportables,
      'export_tables' => $export_tables,
    );
    $output = ctools_build_form('bulk_export_export_form', $form_state);
    if (!$output) {
      drupal_set_title(t('Bulk export results'));
      $output = '';
      $module_code = '';
      $api_code = '';
      $dependencies = array();
      foreach ($form_state['code'] as $module => $api_info) {
        if ($module == 'general') {
          $module_code .= $api_info;
        }
        else {
          foreach ($api_info as $api => $info) {
            $api_code .= "  if (\$module == '$module' && \$api == '$api') {\n";
            $api_code .= "    return array('version' => $info[version]);\n";
            $api_code .= "  }\n";
            $dependencies[$module] = TRUE;

            $file = $form_state['module'] . '.' . $api . '.inc';
            $code = "<?php\n";
            $code .= "// \$Id" . ": $\n\n";
            $code .= "/**\n";
            $code .= " * @file\n";
            $code .= " * Bulk export of $api objects generated by Bulk export module.\n";
            $code .= " */\n\n";
            $code .= $info['code'];
            $output .= drupal_get_form('ctools_export_form', $code, t('Place this in @file', array('@file' => $file)));
          }
        }
      }

      // Add hook_ctools_plugin_api at the top of the module code, if there is any.
      if ($api_code) {
        $api =  "/**\n";
        $api .= " * Implementation of hook_ctools_plugin_api().\n";
        $api .= " */\n";
        $api .= "function $form_state[module]_ctools_plugin_api(\$module, \$api) {\n";
        $api .= $api_code;
        $api .= "}\n";
        $module_code = $api . $module_code;
      }

      if ($module_code) {
        $module =  "<?php\n";
        $module .= "// \$Id" . ": $\n\n";
        $module .= "/**\n";
        $module .= " * @file\n";
        $module .= " * Bulk export of objects generated by Bulk export module.\n";
        $module .= " */\n\n";
        $module .= $module_code;
        $output = drupal_get_form('ctools_export_form', $module, t('Place this in @file', array('@file' => $form_state['module'] . '.module'))) . $output;
      }

      $info  = "; \$Id" . ": $\n"; // The break in the string prevents CVS from subbing the ID.
      $info .= strtr("name = @module export module\n", array('@module' => $form_state['module']));
      $info .= strtr("description = Export objects from CTools\n", array('@module' => $form_state['values']['name']));
      foreach ($dependencies as $module => $junk) {
        $info .= "dependencies[] = $module\n";
      }
      $info .= "package = Chaos tool suite\n";
      $info .= "core = 6.x\n";
      $output = drupal_get_form('ctools_export_form', $info, t('Place this in @file', array('@file' => $form_state['module'] . '.info'))) . $output;

    }
    return $output;
  }
  else {
    return t('There are no objects to be exported at this time.');
  }
}

/**
 * FAPI definition for the bulk exporter form.
 *
 */
function bulk_export_export_form(&$form_state) {
  $form = array();
  $form['tables'] = array(
    '#prefix' => '<div class="clear-block">',
    '#suffix' => '</div>',
    '#tree' => TRUE,
  );

  foreach ($form_state['exportables'] as $table => $list) {
    $form['tables'][$table] = array(
      '#type' => 'checkboxes',
      '#options' => $list,
      '#default_value' => array(),
    );
  }

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Module name'),
    '#description' => t('Enter the module name to export code to.'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Export'),
  );

  $form['#action'] = url('admin/build/bulkexport/results');
  $form['#exportables'] = $form_state['exportables'];
  $form['#export_tables'] = $form_state['export_tables'];
  return $form;
}

/**
 * Display the bulk export form.
 */
function theme_bulk_export_export_form($form) {
  $files = module_rebuild_cache();
  $exportables = $form['#exportables'];
  $export_tables = $form['#export_tables'];
  $output = '';

  foreach ($export_tables as $table => $module) {
    $header = array(theme('table_select_header_cell'), "{$files[$module]->info['name']}: $table");
    $rows = array();
    foreach ($exportables[$table] as $name => $title) {
      // $title = $form['tables'][$table][$name]['#title'];
      unset($form['tables'][$table][$name]['#title']);
      $rows[] = array(drupal_render($form['tables'][$table][$name]), $title);
    }

    if ($rows) {
      $output .= '<div class="export-container">';
      $output .= theme('table', $header, $rows);
      $output .= "</div>\n";
    }
  }

  if (empty($output)) {
    $output = t('There are no objects in your system that may be exported at this time.');
  }

  drupal_add_css(drupal_get_path('module', 'bulk_export') . '/bulk_export.css');
  $output .= drupal_render($form);
  return $output;
}

/**
 * Process the bulk export submit form and make the results available.
 */
function bulk_export_export_form_submit($form, &$form_state) {
  $code = array();
  $name = empty($form_state['values']['name']) ? 'foo' : $form_state['values']['name'];

  foreach ($form_state['values']['tables'] as $table => $names) {
    $names = array_keys(array_filter($names));
    if ($names) {
      natcasesort($names);
      ctools_export_to_hook_code($code, $table, $names, $name);
    }
  }

  $form_state['code'] = $code;
  $form_state['module'] = $name;
}
