<?php

/*
 * Nanogong recorder applet callback. This is what happens when
 * 'upload' is pressed in the applet
 */
function audioprompter_receive($nid) {
  if ($node = node_load($nid)) { // intentional assignment of $node
    if (!user_access('use audioprompter') || !in_array($node->language, audioprompter_get_user_languages())) {
      print(NULL);
      exit();
    }

    header("Cache-control: private");
    header("Content-Type: text/plain");

    if ($_FILES['voicefile']['error']>0) {
      watchdog('audioprompter', "ERROR - error code: " . $_FILES['voicefile']['error']);
      $fid = "NULL";
    }
    else {

      // setup options for drupal_alter()
      $options['convert'] = variable_get('audioprompter_conversion', 'ima');
      $options['scheme'] = variable_get('audioprompter_file_scheme', 'public://');
      $options['directory'] = variable_get('audioprompter_file_directory', '');
      $options['extension'] = in_array($options['convert'], array('ima', 'wavpcm')) ? 'wav' : $options['convert'];
      $options['name'] = time();

      // allow modules to alter the recorded files
      $tempfile = $_FILES['voicefile'];
      drupal_alter('audioprompter_file', $tempfile, $node, $options);

      // convert to a new format if desired / available
      if (!in_array($options['convert'], array('spx', 'ima'))) {
        $tmp_name = $tempfile['tmp_name'];
        $output = $status = '';
        if ($options['convert'] == 'wavpcm') {
          $sox = "sox $tmp_name -b 16 -t wavpcm {$tmp_name}c";
        }
        else {
          $sox = "sox $tmp_name -b 16 -t {$options['convert']} {$tmp_name}c";
        }
        exec($sox, $output, $status);
        if (!$status) {
          exec("mv {$tmp_name}c $tmp_name", $output, $status);
          $tempfile['size'] = filesize($tmp_name);
        }
      }

      // create new filename
      $new_name = file_create_filename("{$options['name']}.{$options['extension']}", $options['scheme'] . $options['directory']);
      $tempfile['name'] = $new_name;

      // setup file for saving
      $_FILES['files'] = $tempfile;
      foreach ($_FILES['files'] as $key => $value) {
        $_FILES['files'][$key] = array(0 => $value);
      }
      $validators['file_validate_extensions'] = array(variable_get('audioprompter_allowed_extensions', 'wav ogg spx'));
      if (!$file = file_save_upload(0, $validators, $options['scheme'] . $options['directory'])) {
        watchdog('audioprompter', "ERROR - file_save_upload failed", array(), WATCHDOG_ERROR);
        $fid = "NULL";
      }
      else {
        drupal_alter('audioprompter_saved_file', $file, $node);
        $fid = $file->fid;
        $field_id = variable_get('audioprompter_filefield', 'field_audio');
        $node->{$field_id}['und'][0]['fid'] = $fid;
        $node->{$field_id}['und'][0]['display'] = 1;
        node_save($node);
      }
    }
    //Return fid to javascript
    print("$fid");
  }
}

function audioprompter_record($form, &$form_state, $langcode = '') {
  // get the language
  if (!$languages = audioprompter_get_user_languages()) {
    return array('denied' => array('#markup' => t("You don't have permission to record audio in any languages.")));
  }
  if (!$langcode) {
    if (!module_exists('translation')) {
      $langcode = 'und';
    }
    else {
      $all_languages = language_list();
      foreach ($languages as $language) {

        $query = audioprompter_nodequery($language);
        if ($count = $query->countQuery()->execute()->fetchField()) {

          $links["audioprompter-record-$language"] = array(
            'title' => ($language == 'und' ? t('(language unspecified)') : $all_languages[$language]->name) . " ($count)",
            'href' => "audioprompter/record/$language",
            'attributes' => array('absolute' => FALSE),
          );

        }
      }

      if (count($links)) {
        drupal_alter('audioprompter_links', $links);
        $form['chooselang'] = array(
          '#markup' => theme('links', array('links' => $links))
        );
      }
      else {
        $form['chooselang'] = array(
          '#markup' => t('There is nothing to record at the moment.')
        );
      }
      return $form;
    }
  }
  if (!in_array($langcode, $languages)) {
    return array('denied' => array('#markup' => t("You don't have permission to record audio in this language.")));
  }

  $form['language'] = array('#type' => 'hidden', '#value' => $langcode);
  if (!$info = audioprompter_next($langcode)) { // intentional assignment of $info
    return array('message' => array('#markup' => t('There are currently no recordings needed for this language.')));
  }

  drupal_add_js(drupal_get_path('module', 'audioprompter') . '/js/audioprompter_nanogong.js');
  drupal_add_css(drupal_get_path('module', 'audioprompter') . '/css/audioprompter.css');
  $form['prompt'] = array(
    '#markup' => '<div id="audioprompter-prompt">' . $info['prompt'] . '</div>'
  );
  $form['nid'] = array('#type' => 'hidden', '#value' => $info['nid']);
  $form['sess'] = array('#type' => 'hidden', '#value' => session_name());
  $form['cook'] = array('#type' => 'hidden', '#value' => $_COOKIE[session_name()]);
  $form['audioprompt-controls'] = array(
    '#markup' =>
      '<div id="audioprompter-controls" class="prompt-ready">' .
        '<div id="audioprompter-controls-cover"> </div>' .
        '<div class="audioprompter-button" id="audioprompter-replayButton">play</div>' .
        '<div class="audioprompter-button audioprompter-recordButton" id="audioprompter-recordButton">record</div>' .
        '<div class="audioprompter-button" id="audioprompter-stopButton">stop</div>' .
        '<div class="audioprompter-button" id="audioprompter-saveButton">next</div>' .
        '<div class="audioprompter-button audioprompter-recordButton" id="audioprompter-reRecordButton">record</div>' .
      '</div>'
  );
  $config = '<param name="ShowSaveButton" value="false" />'; //Disable Save button
  $config .= '<param name="ShowStopButton" value="false" />'; //Disable Save button
  $config .= '<param name="ShowTime" value="true" /> '; //Show Time
  $config .= '<param name="ShowRecordButton" value="false" /> '; //Disable Record button
  $config .= '<param name="ShowSpeedButton" value="false" /> '; //Disable speed button
  if (variable_get('audioprompter_conversion', 'ima') != 'spx') {
    $config .= '<param name="AudioFormat" value="ImaADPCM" />'; //Set file type
  }
  $player_path = base_path() . drupal_get_path('module', 'audioprompter') . '/recorders/nanogong.jar';
  $form['audioprompter_applet'] = array('#markup' => '<div class="nanogong-player" id="audioprompter-applet-wrapper">
          <applet id="audioprompter-applet" archive="' . $player_path . '" code="gong.NanoGong" width="0" height="0">
          ' . $config . '"/> </applet></div>');
  
  return $form;
}

function audioprompter_next($langcode = 'und', $js = NULL) {
  $ret = 0;
  if ($query = audioprompter_nodequery($langcode)) {
    if ($nid = $query->fields('n', array('nid'))->range(0, 1)->execute()->fetchField()) {
      $node = node_load($nid);
      $promptfield = variable_get('audioprompter_promptfield', 'body');
      $build = node_view($node);
      foreach (element_children($build) as $element) {
        if ($element != $promptfield) {
          unset($build[$element]);
        }
      }
      $ret = array('nid' => $node->nid, 'prompt' => drupal_render($build));
    }
    else {
      $ret = array('nid' => 0, 'prompt' => t('There are no more recordings needed for this language.'));
    }
  }
  if ($js == 'js') {
    drupal_json_output($ret);
    exit();
  }
  return $ret;
}

function audioprompter_nodequery($langcode = 'und') {
  $filefield = check_plain(variable_get('audioprompter_filefield', 'field_audio'));
  $textfield = check_plain(variable_get('audioprompter_promptfield', 'body'));
  if ($filefield_def = field_info_field($filefield) && $textfield_def = field_info_field($textfield)) { // intentional assignments
    $filecolumn = "{$filefield}_fid";
    $textcolumn = "{$textfield}_value";
    $query = db_select('node', 'n');
    $query->leftJoin("field_data_$filefield", 'ap_filefield', 'n.nid = ap_filefield.entity_id');
    $query->leftJoin("field_data_$textfield", 'ap_textfield', 'n.nid = ap_textfield.entity_id');
    $query->condition('n.language', $langcode)
            ->isNull("ap_filefield.{$filefield}_fid")
            ->isNotNull("ap_textfield.{$textfield}_value")
            ->addTag('audioprompter_nodequery');
    return $query;
  }
}
