<?php

/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		QTG Testing Module
*/

//-------------------- QTG Test Plan Display ------------------------
/*
 * QTG SETTINGS Tab:  qtg_test_plan_display()
 *
 */

function qtg_test_plan_display($vars = array()) {
  try {

    /*
    if (user_access('administer sabreQMS') == False) {
      return;
    }
    */
    // Need to force the title here otherwise, it only picks up the
    // title for the first tab
    if(isset($vars['title'])) { drupal_set_title($vars['title']); }

    global $simulator_list;


    $table_header = array(
      array( 'data' => 'Plan' ),
      array( 'data' => 'Simulator' ),
      array( 'data' => 'Frequency' ),
      array( 'data' => 'Admin' ),
    );

    $plan_list = _get_qtg_test_plans();

    $i = 0;
    $table_rows = array();

    if ( count($plan_list)) {

      foreach ($plan_list as $row) {

        $groups = _get_qtg_plan_groups($row->qtg_test_plan_id);
        $group_text = '';

        foreach($groups as $g) {
         $group_text .=  '<br />' . $g->group_name . ', ' .
                          t('Next: ') . _st_format_date($g->next_event, 'custom', 'm/d/Y');
        }

        $row_data = array(
          $row->plan_name,
          _st_format_sim_name($row->sim_name, $row->device_id_internal),
          '<span class="qms-test-plan-frequency">' .
            (('Q' == $row->plan_frequency) ? t('Quarterly') : t('Monthly')) .
          ':&nbsp;</span>' . $group_text ,
          _st_generate_options('qtg/plan', $row->qtg_test_plan_id),
        );


        $table_rows[] = array( 'data' => $row_data );
        $i++;
      }
    }

    $content = l( t('Add QTG Test Plan'), 'qtg/plan/add', array('class' => array('qtg-plan-add')) );

    $content .= theme('table', array(
      'header' => $table_header,
      'rows' => $table_rows,
      'empty' => t('None'),
    ));

    return $content;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_test_plan_display() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}    // END ---- qtg_test_plan_display()


//-------------------- QTG Engine Display ------------------------
/*
 * QTG SETTINGS Tab:  qtg_engine_display()
 *
 */

function qtg_engine_display($vars = array()) {

  // Need to force the title here otherwise, it only picks up the
  // title for the first tab
  if(isset($vars['title'])) { drupal_set_title($vars['title']); }

  $table_header = array(
    array( 'data' => t('Engine Description'), 'class' => array('qms-qtg-engine-tbl-desc')),
    array( 'data' => t('Code'), 'class' => array('qms-qtg-engine-tbl-code')),
    array( 'data' => t('Admin'), 'class' => array('qms-results-admin')),
  );


  $engine_list = _get_qtg_engines();


  $i = 0;
  $table_rows = array();

  if ( count($engine_list) ) {
    foreach ($engine_list as $row) {

      $row_data = array(
        $row->engine_desc,
        $row->engine_code,
        _st_generate_options('qtg/engine', $row->engine_type),
      );


      $table_rows[] = array( 'data' => $row_data );
      $i++;
    }
  }

  $content = l( t('Add Engine Type'), 'qtg/engine/add', array('class' => array('qtg-engine-add')) );

  $content .= theme('table', array(
    'header' => $table_header,
    'rows' => $table_rows,
    'empty' => t('None'),
  ));

  return $content;

}  // END ---- qtg_engine_display()


//-------------------- QTG Test Display ------------------------
/*
 * QTG SETTINGS Tab:  qtg_test_display()
 *
 */

function qtg_test_display($vars = array()) {

  try {

    /*
    if (user_access('administer sabreQMS') == False) {
      return;
    }
    */

    // Need to force the title here otherwise, it only picks up the
    // title for the first tab
    if(isset($vars['title'])) { drupal_set_title($vars['title']); }


    $table_header = array(
      array( 'data' => t('Test'), 'class' => array('qms-qtg-test-tbl-code')),
      array( 'data' => t('Description'), 'class' => array('qms-qtg-test-tbl-desc')),
      array( 'data' => t('Engines'), 'class' => array('qms-qtg-test-tbl-engines')),
      array( 'data' => t('Admin'), 'class' => array('qms-results-admin')),
    );

    // Can't use the db_select() object here as we need to do a group_concat()
    // function to combine engines into a single field
    // Get list of qtg tests
    // split the test code into parts to sort separately or it will sort wrong
    $sql = "SELECT td.qtg_test_def_id, td.test_code, td.test_desc,
                   group_concat(e.engine_code separator ', ') AS `engines`
            FROM   {qms_qtg_test_defs} td
            LEFT JOIN {qms_qtg_tests} t ON t.qtg_test_def_id = td.qtg_test_def_id
            LEFT JOIN {qms_qtg_engine_types} e ON t.engine_type = e.engine_type
            GROUP BY td.qtg_test_def_id
            ORDER BY test_code_seg_1, test_code_seg_2, test_code_seg_3, test_code_seg_4";
    $result = db_query($sql);

    $i = 0;
    $table_rows = array();

    foreach ($result as $row) {

      $row_data = array(
        $row->test_code,
        $row->test_desc,
        $row->engines,
        _st_generate_options('qtg/test', $row->qtg_test_def_id),
      );


      $table_rows[] = array( 'data' => $row_data );
      $i++;
    }

    $content = l( t('Add QTG Test'), 'qtg/test/add',
                array('class' => array('qtg-test-add')) );

    $content .= theme('table', array(
      'header' => $table_header,
      'rows' => $table_rows,
      'empty' => t('None'),
    ));

    return $content;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_test_display() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- qtg_test_display()


//-------------------- QTG Test Schedules Form ------------------------

/*
 *  QTG SETTINGS TAB;  qtg_schedules_form()
 *
 *  This tab is a form to handle test-to-group assignments
 *  It is paged over several pages as there are numerous tests
 */
function qtg_schedules_form($form, $form_state, $vars = array()) {
  try {

    // Need to force the title here otherwise, it only picks up the
    // title for the first tab
    if(isset($vars['title'])) { drupal_set_title($vars['title']); }


    $goto_url = current_path();

    $plan_list = _get_qtg_test_plans(($bGetGroups = True));


    // if no test plans found, that's ok, still display list of tests

    drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.qtgschedule.js');


    //--------- Get Test Plan List -------------

    $num_per_page =  QMS_RECORDS_PER_PAGE;

    $table_header = array(
      array( 'data' => t('Test'),
             'field' => 'test_code_sort',
             //'sort' => 'asc',
             'class' => array('qms-qtg-schedules-tbl-code'),
           ),
      array( 'data' => t('Description, Simulator and Engines'),
             'class' => array('qms-qtg-schedules-tbl-desc'),
           ),
      array( 'data' => t('Group Assignment'),
             'class' => array('qms-qtg-schedules-tbl-groups'),
           ),
//      array( 'data' => t('Admin'),
//             'class' => array('qms-admin'),
//           ),
    );

    $search_init = array(
      'table_name' => 'qms_qtg_test_defs',
      'table_alias' => 'td',
      'table_header' => $table_header,
      'pager_path' => 'qmssettings/qtg/schedules',
      'order' => 'test_code_seg_1',
      'sort' => 'asc',
      'no_header_sort' => True,
    );

    $query = _st_setup_paged_search($search_init);

    $query->orderBy('test_code_seg_1', 'ASC')
          ->orderBy('test_code_seg_2', 'ASC')
          ->orderBy('test_code_seg_3', 'ASC')
          ->orderBY('test_code_seg_4', 'ASC');
//    $query->addExpression('CONCAT_WS(\'.\', test_code_seg_1, test_code_seg_2, test_code_seg_3, test_code_seg_4)', 'test_code_sort');

    // Can't use the db_select() object here as we need to do a group_concat()
    // function to combine engines into a single field
    // Get list of qtg tests
    //$query->leftJoin('qms_qtg_tests', 't', 't.qtg_test_def_id = td.qtg_test_def_id');

    $query->fields('td', array('qtg_test_def_id', 'test_code', 'test_desc',
                               'test_code_seg_1', 'test_code_seg_2',
                               'test_code_seg_3', 'test_code_seg_4'));


    $max_count = 0;
    $result = _st_execute_paged_search($query, $max_count);

    $i = 0;
    $table_rows = array();
    $records = array();

    if ( $result->rowCount() ) {
      // retrieve all so that we can do additional queries in the loop
      $records = $result->fetchAll();

      // IDM -- $records, here, are objects that look like:
      /*
        {
          qtg_test_dev_id => string
          test_code => string
          test_desc => string 'stopping -- brake temperature effects'
          test_code_seg_1 => string
          test_code_seg_2
          test_code_seg_3
          test_code_seg_4
        }
      */
    }

    foreach ($records as $row) {

      // display each test definition
      $row_data = array(
        $row->test_code,
        $row->test_desc,
        '&nbsp;',
      );
      $table_rows[] = array( 'data' => $row_data );
      unset($row_data);
      $i++;

      // get the engine list for this test
      $engine_list = _get_qtg_test_engines($row->qtg_test_def_id);


      if ( count($plan_list) ) {
        /*
          $plan list is an array of objects:
          {
            qtg_test_plan_id => string 2
            plan_name => Falcon 20-F
            simulator_id => string
            plan_frequency=> string Q
            sim_name => Falcon 20-F
            device_id_internal => string
            groups {
                0
            }
          }
        */
        foreach ($plan_list as $p) {

          $check_array = [
            'plan' => $p,
            'sim_name' => $p->sim_name,
            'engine_list' => $engine_list,
          ];

          $sim_name = _st_format_sim_name($p->sim_name, $p->device_id_internal);
          $group_checkboxes = '';


          if ( count($engine_list)) {

            foreach ($engine_list as $eng) {

              // get the groups this test is assigned
              $group_assigns = _get_qtg_test_groups($eng->qtg_test_id);


              $group_checkboxes = '<div class="qms-qtg-group-checkboxes">';

              foreach($p->groups as $g) {

                $group_checkboxes .= '<div class="qms-qtg-group-checkbox"><p>' .
                                    $g->group_name . '</p>';

                $group_checkboxes .= theme('checkbox', array('element' => array(
                  '#name' => 'chk_test_' . $eng->qtg_test_id .
                             '_plan_' . $p->qtg_test_plan_id .
                             '_group_' . $g->qtg_group_id,
                  '#id' =>   'chk_test_' . $eng->qtg_test_id .
                             '_plan_' . $p->qtg_test_plan_id .
                             '_group_' . $g->qtg_group_id,
                  '#checked' => (isset($group_assigns[$g->qtg_group_id])? True : False),
                )));



                $group_checkboxes .= '</div>';
              }
              $group_checkboxes .= theme('textfield', array('element' => array(
                  '#id' =>   'id_test_' . $eng->qtg_test_id .
                             '_plan_' . $p->qtg_test_plan_id,
                  '#name' => 'id_test_' . $eng->qtg_test_id .
                             '_plan_' . $p->qtg_test_plan_id,
                  '#type' => 'textfield',
                  '#value' => $eng->qtg_test_id . '_' . $p->qtg_test_plan_id,
                  '#autocomplete_path' => '',
                  '#attributes' => array('class' => array('qms-hidden')),
                )));
              $group_checkboxes .= '</div>';

              $group_data = array(
                '&nbsp;',
                '<span class="qms-qtg-test">' .
                      $sim_name . ': ' . $eng->engine_code .
                '</span>',
                $group_checkboxes,
              );
              $table_rows[] = array( 'data' => $group_data,
                                     'class' => array('qms-qtg-schedules-tbl-row') );
              $i++;
            }
          }
          else {
            $row_data = array(
                '&nbsp;',
                '<span class="qms-qtg-test">' .
                      $sim_name .
                '</span>',
                '&nbsp;',
              );
              $table_rows[] = array( 'data' => $row_data );
              unset($row_data);
              $i++;
          }
        }
      }

    }

    $content = '<br><div class="qms-desc qms-box">' .
                t('Click "Submit" to save settings changes to this page before proceeding.') .
                '</div>';

    $content .= '<div id="qms-qtg-schedules-div">';

    $content .= theme('table', array(
      'header' => $table_header,
      'rows' => $table_rows,
      'empty' => t('None'),
    ));

    $content .= theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
    $content .= '</div>';

    $content .= '<br><div class="qms-desc qms-box">' .
                t('Click "Submit" to save settings changes to this page before proceeding.') .
                '</div>';


    $form['qtg_test_schedules'] = array(
      '#markup' => $content,
    );

    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#attributes' => array('class' => array('qms-btn-submit')),
    );


    return $form;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_schedules_form() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
} // END -- qtg_schedules_form


/*
 *  qtg_schedules_form_submit()
 *
 *  -- no validation is performed here.  QTG tests are either assigned to groups or not
 *  -- page built by forcing checkboxes through theme('checkbox', ...) so we handle the
 *     return input through $_POST and not $form_state['values']
 *  -- for each test, group assignments are first removed, then added for groups that are selected
 *  -- POST only contains checkboxes that have been turned 'on'
 *
 */
function qtg_schedules_form_submit($form, $form_state) {
  try {

    ksort($_POST);
    $test_id = 0;
    $plan_id = 0;
    $bUpdated = False;

    foreach($_POST as $input => $value) {
      // only process the $_POST elements that match the id_* name pattern
      // one id input element will appear for each qtg_test
      if ( preg_match('/id_test_[0-9]+_plan_[0-9]+/', $input) ) {
        // there will be one id_ field for each test
        // delete group links for each test & plan, then relink
        $ids = explode('_', $value); // $value contains only the ids test_plan (ie. 123_56)

        $test_id = (int)$ids[0];
        $plan_id = (int)$ids[1];

        // for each test, delete the previous test/group releationships

        $num_del = db_delete('qms_qtg_groups_tests')
                ->condition('qtg_test_id', $test_id)
                ->where('qtg_group_id IN
                         (SELECT qtg_group_id FROM qms_qtg_groups WHERE qtg_test_plan_id IN (:pid))',
                          array(':pid' => $plan_id))
								->execute();

        $bUpdated = True;
      }

      if ( $test_id && $plan_id ) {
        foreach($_POST as $input => $value) {
          // only process the $_POST elements that match the checkbox name pattern
          // for the current test & plan
          if ( preg_match('/chk_test_' . $test_id . '_plan_' . $plan_id . '_group_[0-9]+/', $input) ) {
            // now create new test/group relationships for each test where a group has been checked 'on'

            // here we need to grab the group id from the $input key
            // group_id will be the last array element after explode executes
            $ids = explode('_', $input);
            $n = count($ids);
            $group_id = (int)$ids[$n-1];
            $new_id = 0;

            if ( $group_id ) {
              $new_id = db_insert('qms_qtg_groups_tests')
                        ->fields(array(
                          'qtg_test_id' => $test_id,
                          'qtg_group_id' => $group_id,
                        ))->execute();

              $bUpdated = True;
            }
          }
        }
        $test_id = 0;
        $plan_id = 0;
      }
    }
    if ( $bUpdated ) {
      drupal_set_message(t('QTG Schedule settings saved successfully.'));
    }
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_schedules_form_submit() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}


//-------------------- QTG Plan Form ---------------------

/*
 *    qtg_plan_form()
 *
 */
function qtg_plan_form($form, $form_state, $qtg_test_plan_id = 0) {


  $plan = (object) Null;
  $groups = array();
  $next_monthly_date = 0;
  $next_qtr_date = 0;
  $next_group = '';

  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg';
	}



  // edit existing Test Plan
  if ( $qtg_test_plan_id ) {

    $plan = _get_qtg_test_plan($qtg_test_plan_id);

    if ( $plan == (object) Null ) {
			drupal_set_message( t('QTG Test Plan Not Found!'), 'warning');
			drupal_goto($goto_url);
			return;
		}

    $groups = _get_qtg_plan_groups($qtg_test_plan_id);
    if ( !count($groups) ) {
			drupal_set_message( t('QTG Test Groups Not Found!'), 'warning');
			drupal_goto($goto_url);
			return;
		}


    $form['plan_timestamps'] = array(
			'#markup' => _st_format_record_timestamp_table($plan),
		);
  }

  $form['#after_build'][] = 'qtg_plan_form_after_build';



  $form['plan_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Plan Name'),
		'#maxlength' => 50,
    '#size' => 50,
    '#required' => True,
		'#default_value' => (($qtg_test_plan_id > 0) ?
                          $plan->plan_name : ''),
    '#attributes' => array('id' => 'qms-qtg-plan-name'),
	);


  $form['plan_active'] = array(
    '#type' => 'checkbox',
    '#title' => t('Active?'),
    '#default_value' => (($qtg_test_plan_id > 0) ? (int) $plan->active : 1),
    '#disabled' => (($qtg_test_plan_id > 0) ? False : True),
  );

  $freq_list = array(
    //0 => '- ' . t('Select') . ' -',
    'M' => t('Monthly'),
    'Q' => t('Quarterly'),
  );

  // setting up a new plan
  if ( !$qtg_test_plan_id ) {

    $qtg_sim_list = new SimulatorList(array('omit_if_qtg' => True));

    $form['simulator'] = array(
      '#type' => 'select',
      '#title' => t('Simulator'),
      '#options' => $qtg_sim_list->get(),
      '#default_value' => (($qtg_test_plan_id > 0) ?
                            $plan->simulator_id : 0),
      '#required' => True,
      '#attributes' => array('class' => array('qms-select'),
                             'id' => 'qms-simulator-select'),
    );


    $form['frequency'] = array(
      '#type' => 'select',
      '#title' => t('Frequency'),
      '#options' => $freq_list,
      '#default_value' => 'Q',
      '#required' => True,
      '#attributes' => array('class' => array('qms-select'),
                             'id' => 'qms-frequency-select'),
    );

  }
  else {
    global $simulator_list;

    $form['simulator'] = array(
      '#type' => 'item',
      '#title' => t('Simulator'),
      '#markup' => $simulator_list->getName($plan->simulator_id),
    );

    $form['frequency'] = array(
      '#type' => 'item',
      '#title' => t('Frequency'),
      '#markup' => $freq_list[$plan->plan_frequency] .
                   '<span id="qms-frequency-code" class="qms-hidden">' .
                      $plan->plan_frequency .
                    '</span>',
    );

    $form['frequency_code'] = array(
      '#type' => 'textfield',
      '#default_value' => $plan->plan_frequency,
      '#attributes' => array('class' => array('qms-hidden'),
                             'id' => 'qms-frequency-code'),

    );


  }

  // display Test Plan Groups

  $form['groups_table_begins'] = array(
		'#markup' => '<hr /><h3>' . t('Test Groups') . '</h3>' .
								 '<table id="qms-qtg-groups-tbl" class="qms-plain-table">',
	);

  // fake the field requirement as not all of these will be populated if
  // handled quarterly
  $reqd_text = '<span class="form-required" title="' .
                  t('This field is required.') . '"> *</span>';

  if ( !count($groups) ) {
    //$next_monthly_date = strtotime('first day of next month');
    $next_monthly_date = _st_modify_timestamp(0, 'first day of next month');
    $next_qtr_date = $next_monthly_date;
    $next_group = 'A';
  }

  for($i=0; $i<12; $i++) {

		$form['group_name_' . $i] = array(
			'#type' => 'textfield',
			'#title' => t('Group Name') . ' ' . ($i + 1) . $reqd_text,
			'#maxlength' => 50,
			'#size' => 25,
			'#default_value' =>
          (isset($groups[$i]->group_name) ? $groups[$i]->group_name : $next_group),
			'#attributes' => array('class' => array('qms-group-name-' . $i)),
			'#prefix' => '<tr id="qms-qtg-group-row-' . $i . '"><td>',
			'#suffix' => '</td>',
		);



    $form['next_event_' . $i] = array(
      '#type' => 'date_popup',
      '#title' => t('Next Deployment Date') . $reqd_text,
      '#size' => 12,
      '#date_format' => 'm-d-Y',						// displayed format
        //default value has to be in this format
      '#default_value' => ( isset($groups[$i]->next_event) ?
                  _st_format_date($groups[$i]->next_event, 'custom', 'Y-m-d') :
                  _st_format_date($next_monthly_date, 'custom', 'Y-m-d')),
      '#required' => False,   // if no date entered, returns NULL
      '#attributes' => array('class' => array('qms-date-picker'),
                              'id' => 'qms-next-event-date-' . $i),
      '#prefix' => '<td><div class="qms-next-deploy-event">',
      '#suffix' => '</div></td>',
    );

    $form['groups_table_hidden_1'] = array(
      '#markup' => '<td>',
    );

    if ( $i < 4 ) {
      $form['q_date_' . $i] = array(
        '#type' => 'textfield',
        '#default_value' => _st_format_date($next_qtr_date, 'custom', 'm-d-Y'),
        '#attributes' => array('class' => array('qms-hidden'),
                               'id' => 'qms-q-date-' . $i),
      );
      $form['m_date_' . $i] = array(
        '#type' => 'textfield',
        '#default_value' => _st_format_date($next_monthly_date, 'custom', 'm-d-Y'),
        '#attributes' => array('class' => array('qms-hidden'),
                               'id' => 'qms-m-date-' . $i),
      );
    }


		$form['group_id_' . $i] = array(
			'#type' => 'textfield',
			'#default_value' => isset($groups[$i]->qtg_group_id) ?
              $groups[$i]->qtg_group_id : 0,
			'#attributes' => array('class' => array('qms-hidden'),
                             'id' => 'qms-qtg-group-id-' . $i),
		);

    $form['groups_table_hidden_2'] = array(
      '#markup' => '</td></tr>',
    );



    if ( !count($groups) ) {
      //$next_monthly_date = strtotime('+1 month', $next_monthly_date);
      $next_monthly_date = _st_modify_timestamp($next_monthly_date, '+1 month');
      //$next_qtr_date = strtotime('+3 months', $next_qtr_date);
      $next_qtr_date = _st_modify_timestamp($next_qtr_date, '+3 months');
      $next_group = chr(($i+1+65));
    }
	}


  $form['groups_table_ends'] = array(
		'#markup' => '</tr></table><hr />',
	);


  $form['qtg_test_plan_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $qtg_test_plan_id,
    '#attributes' => array('id' => 'qms-qtg-test-plan-id',
                           'class' => array('qms-hidden')),
	);

  $form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#name' => 'submit',
		'#attributes' => array('class' => array('qms-btn-submit')),
	);


  $form['actions']['done'] = array(
		'#type' => 'submit',
		'#value' => t('Done'),
    '#name' => 'done',
		'#attributes' => array('class' =>
                              array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                              url($goto_url) . '"; return false;'),
	);

  return $form;
}  // END ---- qtg_plan_form()



/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it.
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/*
 * qtg_plan_form_after_build()
 *
 */

function qtg_plan_form_after_build($form, &$form_state) {
	drupal_add_library('system','ui.datepicker');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.qtgplans.js');

	return $form;
}  // END ---- qtg_plan_form_after_build()



/*
 *	qtg_plan_form_validate()
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates form after it is submitted
 */

function qtg_plan_form_validate($form, $form_state) {

  if ( trim($form_state['values']['plan_name']) == '' ) {
		form_set_error('plan_name', t('Plan Name is a required field.'));
	}
  if ( isset($form_state['values']['simulator']) ) {
    if ( 0 == (int)$form_state['values']['simulator'] ) {
      form_set_error('simulator', t('Simulator is a required field.'));
    }
  }
  if ( isset($form_state['values']['frequency']) ) {

    $num_groups = (($form_state['values']['frequency'] == 'Q') ? 4 : 12);
    for ( $g=0; $g < $num_groups; $g++ ) {
      if ( $form_state['values']['group_name_' . $g] == '' ) {
        form_set_error('group_name_' . $g, t('Group Names are required fields.'));
        break;
      }
      if ( $form_state['values']['next_event_' . $g] == '' ) {
        form_set_error('next_event_' . $g, t('Next Deployment Date is required.'));
        break;
      }
    }
  }
}  // END ---- qtg_plan_form_validate()

/*
 *	qtg_plan_form_submit()
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves customer_form data upon successful submit
 */

function qtg_plan_form_submit($form, $form_state) {

  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg';
	}

  $plan = new stdClass();
  global $user;
  $id = '';

  $qtg_test_plan_id = (int)$form_state['values']['qtg_test_plan_id'];
  $plan->plan_name = $form_state['values']['plan_name'];
  $plan->active = (int)$form_state['values']['plan_active'];

  if ( isset($form_state['values']['simulator']) ) {
    $plan->simulator_id = (int)$form_state['values']['simulator'];
  }
  if ( isset($form_state['values']['frequency']) ) {
    $plan->plan_frequency = $form_state['values']['frequency'];
  }
  else {
    $plan->plan_frequency = $form_state['values']['frequency_code'];
  }

  if ( $qtg_test_plan_id ) {
    // edit
    $plan->qtg_test_plan_id = $qtg_test_plan_id;
    $id = 'qtg_test_plan_id';
    $plan->updated_date = REQUEST_TIME;
    $plan->updated_by_user = $user->uid;
  }
  else {
    // new
    $id = array();
    $plan->active = 1;
    $plan->created_date = REQUEST_TIME;
    $plan->created_by_user = $user->uid;
  }

  //--------- Save QTG Test Plan ------------

  // new record
  if ( False == drupal_write_record('qms_qtg_test_plans', $plan, $id)) {
			$msg = "Oops!  Something went wrong saving the QTG Test Plan record.";
			drupal_set_message(t($msg));
      return;
  }


  //--------- Save QTG Groups ----------------

  $group = new stdClass();
  $num_groups = (($plan->plan_frequency == 'Q') ? 4 : 12);
  $id = array();

  for ( $g=0; $g < $num_groups; $g++) {

    $group_id = (int)$form_state['values']['group_id_' . $g];
    $group->qtg_test_plan_id = $plan->qtg_test_plan_id;
    $group->group_name = $form_state['values']['group_name_' . $g];
    $next_event = $form_state['values']['next_event_' . $g];
    $group->next_event = _st_format_timestamp($next_event . ' 00:00:00');

    if ( $group_id ) {
      $group->qtg_group_id = $group_id;
      $id = 'qtg_group_id';
    }
    if ( False == drupal_write_record('qms_qtg_groups', $group, $id)) {
      $msg = "Oops!  Something went wrong saving the QTG Test Groups.";
      drupal_set_message(t($msg));
      return;
    }
    unset($group->qtg_group_id);
  }

	drupal_set_message(t("QTG Test Plan successfully saved."));

  //---------- Routing -----------------------

  drupal_goto($goto_url);
}  // END ---- qtg_test_plan_form_submit()



/*
 *	qtg_test_plan_delete_confirm()
 *
 *	Validate and Ask for confirmation before deleting record
 */

function qtg_plan_delete_confirm($form, $form_state, $qtg_test_plan_id = 0) {

  try {

    if ( !$qtg_test_plan_id ) {
      drupal_set_message(
          t('Oops! Something went wrong. QTG Test Plan Id invalid.'));
      drupal_goto($goto_url);
      return;
    }

    $goto_url = 'qmssettings/qtg';
    $msg = '';

    $plan = _get_qtg_test_plan($qtg_test_plan_id);

    if ( Null == $plan ) {
      drupal_set_message(t('Oops! Something went wrong. QTG Test Plan not found.'));
      drupal_goto($goto_url);
      return;
    }

    $sql = "SELECT qtg_event_id FROM {qms_qtg_events}
              WHERE qtg_test_plan_id = :id LIMIT 1";
    $result = db_query($sql, array(':id' => $qtg_test_plan_id));
    if ( $result->rowCount() ) {
      // cannot delete, linkage found
      $msg = "Unable to delete " . $plan->plan_name .
              ".  Test Plan is linked to QTG test records.  " .
              "If you proceed, test plan will be retained, but set to 'inactive'.";
      drupal_set_message(t($msg));
    }


    $form['qtg_test_plan_id'] = array(
      '#type' => 'value',
      '#value' => $qtg_test_plan_id,
    );

    $form['plan_name'] = array(
      '#type' => 'value',
      '#value' => $plan->plan_name,
    );

    if ( !strlen($msg)) {
      $msg = t('This action cannot be undone.');
    }

    $title = t('Delete QTG Test Plan') . '?';
    $question = t('Are you sure you want to delete?') .
                '<h2>' . $plan->plan_name . '</h2><br />' .
                $msg;
    $goto_if_canceled = $goto_url;
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    // force this here to avoid a problem with routing if cancelled
    //$_GET['destination'] = $goto_if_canceled;

    return confirm_form($form, $title,	$goto_if_canceled, $question,
                        $yes_btn, $no_btn);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_plan_delete_confirm()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}

/*
 *	qtg_test_plan_delete_confirm_submit()
 *
 *	Submit after confirmation, delete the specified record
 */

function qtg_plan_delete_confirm_submit($form, $form_state) {

  try {

    $goto_url = 'qmssettings/qtg';

    if ( $form_state['values']['confirm']) {
      $qtg_test_plan_id = $form_state['values']['qtg_test_plan_id'];
      $plan_name = $form_state['values']['plan_name'];


      // delete from database
      $subquery = db_select('qms_qtg_groups', 'g')
                  ->condition('g.qtg_test_plan_id', $qtg_test_plan_id);
      $subquery->addField('g', 'qtg_group_id');

      $num_tests = db_delete('qms_qtg_groups_tests')
                  ->exists($subquery)
                  ->execute();

      $num_plans = db_delete('qms_qtg_test_plans')
                  ->condition('qtg_test_plan_id', $qtg_test_plan_id)
                  ->execute();

      $num_groups = db_delete('qms_qtg_groups')
                  ->condition('qtg_test_plan_id', $qtg_test_plan_id)
                  ->execute();

      $msg = 'QTG Test Plan record, ' . $plan_name . ' has been deleted.';

      drupal_set_message(t($msg));
    }

    drupal_goto($goto_url);
  }
  catch (Exception $e) {
    watchdog('sabreQMS', 'qtg_plan_delete_confirm_submit()' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}






//---------------- QTG Engine Form ----------------------------
/*
 *    qtg_engine_form()
 *
 */
function qtg_engine_form($form, $form_state, $engine_type = 0) {


  $engine = (object) Null;

  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg/engines';
	}

  drupal_add_js('(function($) {
										Drupal.behaviors.qmsEngineForm = {
											attach: function(context, settings) {
												$("#qms-qtg-engine-desc", context).focus();
											}
										}
									}(jQuery));', 'inline');


  // edit existing engine
  if ( $engine_type ) {

    $engine = _get_qtg_engine($engine_type);

    if ( $engine == (object) Null ) {
			drupal_set_message( t('QTG Engine Not Found!'), 'warning');
			drupal_goto($goto_url);
			return;
		}

  }


  $form['engine_desc'] = array(
		'#type' => 'textfield',
		'#title' => t('Engine Description'),
		'#maxlength' => 25,
    '#size' => 25,
    '#required' => True,
		'#default_value' => (($engine_type > 0) ?
                          $engine->engine_desc : ''),
    '#attributes' => array('id' => 'qms-qtg-engine-desc'),
	);

  $form['engine_code'] = array(
		'#type' => 'textfield',
		'#title' => t('Engine Code'),
		'#maxlength' => 5,
    '#size' => 5,
    '#required' => True,
		'#default_value' => (($engine_type > 0) ?
                          $engine->engine_code : ''),
    '#attributes' => array('id' => 'qms-qtg-engine-code'),
	);

  $form['engine_type'] = array(
		'#type' => 'textfield',
		'#default_value' => $engine_type,
    '#attributes' => array('id' => 'qms-qtg-engine-type',
                           'class' => array('qms-hidden')),
	);

  $form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#name' => 'submit',
		'#attributes' => array('class' => array('qms-btn-submit')),
	);


  $form['actions']['done'] = array(
		'#type' => 'submit',
		'#value' => t('Done'),
    '#name' => 'done',
		'#attributes' => array('class' =>
                              array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                              url($goto_url) . '"; return false;'),
	);

  return $form;
}  // END ---- qtg_engine_form()



/*
 *	qtg_engine_form_validate()
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates form after it is submitted
 */

function qtg_engine_form_validate($form, $form_state) {

  if ( trim($form_state['values']['engine_desc']) == '' ) {
		form_set_error('engine_desc', t('Engine Description is a required field.'));
	}
  if ( trim($form_state['values']['engine_code']) == '' ) {
		form_set_error('engine_code', t('Engine Code is a required field.'));
	}

}  // END ---- qtg_engine_form_validate()

/*
 *	qtg_engine_form_submit()
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves customer_form data upon successful submit
 */

function qtg_engine_form_submit($form, $form_state) {

  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg/engines';
	}

  $engine = new stdClass();
  $id = '';

  $engine_type = (int)$form_state['values']['engine_type'];
  $engine->engine_desc = $form_state['values']['engine_desc'];
  $engine->engine_code = $form_state['values']['engine_code'];



  if ( $engine_type ) {
    // edit
    $engine->engine_type = $engine_type;
    $id = 'engine_type';
  }
  else {
    // new
    $id = array(); // id to be auto generated, do not provide one
  }

  //--------- Save QTG Engine Type ------------

  // new record
  if ( False == drupal_write_record('qms_qtg_engine_types', $engine, $id)) {
			$msg = "Oops!  Something went wrong saving the QTG Engine record.";
			drupal_set_message(t($msg));
      return;
  }

  drupal_set_message(t("QTG Engine successfully saved."));


  //---------- Routing -----------------------

  drupal_goto($goto_url);
}  // END ---- qtg_test_plan_form_submit()



/*
 *	qtg_engine_delete_confirm()
 *
 *	Validate and Ask for confirmation before deleting record
 */

function qtg_engine_delete_confirm($form, $form_state, $engine_type = 0) {

  try {

    if ( !$engine_type ) {
      drupal_set_message(
          t('Oops! Something went wrong. Invalid QTG Engine Type.'));
      drupal_goto($goto_url);
      return;
    }

    $goto_url = 'qmssettings/qtg/engines';
    $msg = '';

    $engine = _get_qtg_engine($engine_type);

    if ( Null == $engine ) {
      drupal_set_message(t('Oops! Something went wrong. QTG Engine not found.'));
      drupal_goto($goto_url);
      return;
    }


    $sql = "SELECT qtg_test_id FROM {qms_qtg_tests}
              WHERE engine_type = :id LIMIT 1";
    $result = db_query($sql, array(':id' => $engine_type));
    if ( $result->rowCount() ) {
      // cannot delete, linkage found
      $msg = "Unable to delete " . $engine->engine_desc .
              ".  Engine is linked to QTG tests.  ";
      drupal_set_message(t($msg));
      drupal_goto($goto_url);
      return;
    }


    $form['engine_type'] = array(
      '#type' => 'value',
      '#value' => $engine_type,
    );

    $form['engine_desc'] = array(
      '#type' => 'value',
      '#value' => $engine->engine_desc,
    );

    $form['engine_code'] = array(
      '#type' => 'value',
      '#value' => $engine->engine_code,
    );


    $title = t('Delete QTG Engine') . '?';
    $question = t('Are you sure you want to delete?') .
                '<h2>' . $engine->engine_desc . '</h2><br />' .
                t('This action cannot be undone.');
    $goto_if_canceled = $goto_url;
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    // force this here to avoid a problem with routing if cancelled
    //$_GET['destination'] = $goto_if_canceled;

    return confirm_form($form, $title,	$goto_if_canceled, $question,
                        $yes_btn, $no_btn);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_engine_delete_confirm_submit()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}

/*
 *	qtg_engine_delete_confirm_submit()
 *
 *	Submit after confirmation, delete the specified record
 */

function qtg_engine_delete_confirm_submit($form, $form_state) {

  try {

    $goto_url = 'qmssettings/qtg/engines';

    if ( $form_state['values']['confirm']) {
      $engine_type = $form_state['values']['engine_type'];
      $engine_code = $form_state['values']['engine_code'];
      $engine_desc = $form_state['values']['engine_desc'];


      // delete from database
      $num_plans = db_delete('qms_qtg_engine_types')
                  ->condition('engine_type', $engine_type, '=')
                  ->execute();

      $msg = 'QTG Engine, ' . $engine_desc . ' has been deleted.';

      drupal_set_message(t($msg));
    }

    drupal_goto($goto_url);
  }
  catch (Exception $e) {
    watchdog('sabreQMS', 'qtg_engine_delete_confirm_submit()' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}


//-------------------- QTG Test Form ------------------------
/*
 *  qtg_test_form()
 */
function qtg_test_form($form, $form_state, $qtg_test_def_id = 0) {

  $test = (object) Null;
  $test_engines = array(); // engines linked to this test
  $engine_list = array();

  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg/tests';
	}


  // edit existing test definition
  if ( $qtg_test_def_id ) {

    $test = _get_qtg_test_definition($qtg_test_def_id);

    if ( $test == (object) Null ) {
			drupal_set_message( t('QTG Test Definition Not Found!'), 'warning');
			drupal_goto($goto_url);
			return;
		}

    $test_engines = _get_qtg_test_engines($qtg_test_def_id);
    // it's OK if no engines are found here... config'ed on a diff tab
  }

  $engine_list = _get_qtg_engines();

  if ( !count($engine_list) ) {
			drupal_set_message( t('QTG Engines Not Found!  Engines must be defined before configuring with tests.'), 'warning');
			drupal_goto('qmssettings/qtg/engines');
			return;
	}

  $form['#after_build'][] = 'qtg_test_form_after_build';

  // allow for 1st & 3rd numeric positions to be 2 char or 1
  $test_code = ($qtg_test_def_id ?
                (((strlen($test->test_code_seg_1) == 1) ? '0' : '') .
                 $test->test_code_seg_1 . '.' .
                 $test->test_code_seg_2 . '.' .
                 ((strlen($test->test_code_seg_3) == 1) ? '0' : '') .
                 $test->test_code_seg_3  . '.' .
                 $test->test_code_seg_4) :
                 '');

  $form['test_code'] = array(
		'#type' => 'textfield',
		'#title' => t('Test Code'),
		'#maxlength' => 20,
    '#size' => 15,
    '#required' => True,
		'#default_value' => $test_code,
    '#attributes' => array('id' => 'qms-qtg-test-code'),
    '#suffix' => '<div class="qms-desc">' . t('Format') . ':  99.a.99.9' . '</div><br/>',
	);

  $form['test_desc'] = array(
		'#type' => 'textfield',
		'#title' => t('Test Description'),
		'#maxlength' => 255,
    '#size' => 70,
    '#required' => True,
		'#default_value' => ($qtg_test_def_id ?
                          $test->test_desc : ''),
    '#attributes' => array('id' => 'qms-qtg-test-desc'),

	);

  $engine_opts = array();
  $engine_values = array();

  foreach($engine_list as $eng) {
    $engine_opts[$eng->engine_type] = $eng->engine_code . ': ' . $eng->engine_desc;
  }

  if ( count($test_engines) ) {
    foreach($test_engines as $eng) {
      $engine_values[] = $eng->engine_type;
    }
  }
  $form['engines'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Engines'),
      '#options' => $engine_opts,
      '#default_value' => $engine_values,
      '#attributes' => array('id' => 'qms-qtg-engines-chk'),
    );


  $form['qtg_test_def_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $qtg_test_def_id,
    '#attributes' => array('id' => 'qms-qtg-test-def_id',
                           'class' => array('qms-hidden')),
	);

  $form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#name' => 'submit',
		'#attributes' => array('class' => array('qms-btn-submit')),
	);


  $form['actions']['done'] = array(
		'#type' => 'submit',
		'#value' => t('Done'),
    '#name' => 'done',
		'#attributes' => array('class' =>
                              array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                              url($goto_url) . '"; return false;'),
	);

  return $form;
} // END -- qtg_test_form()



/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it.
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/*
 * qtg_test_form_after_build()
 *
 */

function qtg_test_form_after_build($form, &$form_state) {
	//drupal_add_library('system','ui.datepicker');
  //
  // see http://digitalbush.com/projects/masked-input-plugin/
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/vendor/jquery.maskedinput-1.3.1.min.js');
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.qtgtests.js');

	return $form;
}  // END ---- qtg_test_form_after_build()



/*
 *  qtg_test_form_validate()
 */
function qtg_test_form_validate($form, $form_state) {

  $qtg_test_def_id = (int)$form_state['values']['qtg_test_def_id'];
  $test_code = trim($form_state['values']['test_code']);

  // strip zero padding from first segment
  if ($test_code[0] == '0') {
    $test_code = substr($test_code, 1);
  }

  $sort_keys = explode('.', $test_code);
  $test_code_seg = array();
  $test_code_seg[] = (int)$sort_keys[0];
  $test_code_seg[] = (isset($sort_keys[1]) ? $sort_keys[1] : NULL);

  if (isset($sort_keys[2]) && ((int)$sort_keys[2] > 0)) {
    $test_code_seg[] = (int)$sort_keys[2];
  }
  if (isset($sort_keys[3]) && ((int)$sort_keys[3] > 0)) {
    $test_code_seg[] = $sort_keys[3];
  }

  $test_code = implode('.', $test_code_seg);

  if ( '' == $test_code ) {
    form_set_error('test_code', t('Test Code is a required field.'));
  }
  if ( !$test_code_seg[0] || (Null == $test_code_seg[1]) ) {
    form_set_error('test_code', t('Test Code entered is invalid.'));
  }
  if (False == _is_test_code_unique($qtg_test_def_id, $test_code)) {
    form_set_error('test_code', t('Test Code already exists.'));
  }

  if ( '' == trim($form_state['values']['test_desc'])) {
    form_set_error('test_desc', t('Test Desc is a required field.'));
  }

  // block removing engines from tests that have already occurred

  $sel_engines = $form_state['values']['engines'];

  if ( $qtg_test_def_id ) {
    $engine_list = new EngineTypes();

    foreach($sel_engines as $engine_type => $selected) {
      if ( $engine_type != $selected ) { // engine was not selected or deselected

        if ( _has_qtg_test_event($qtg_test_def_id, $engine_type) ) {

          $msg =  t('Unable to remove engine') . ', ' . $engine_list->getName($engine_type) . '. ' .
                  t('Engine is linked to QTG Test Events.');

          form_set_error('engines', $msg);
        }
      }
    }
  }

  // DEBUG

  //form_set_error('engines', 'Debug-breakpoint');
}

/*
 *  qtg_test_form_submit()
 */
function qtg_test_form_submit($form, $form_state) {


  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg/tests';
	}

  $test = new stdClass();
  $id = '';
  $bNew = False;

  $qtg_test_def_id = (int)$form_state['values']['qtg_test_def_id'];
  $test->test_desc = $form_state['values']['test_desc'];
  $test->test_code = $form_state['values']['test_code'];

  $sort_keys = explode('.', $test->test_code);
  $test->test_code_seg_1 = (int)$sort_keys[0];
  // strip leading zero
  $sort_keys[0] = "{$test->test_code_seg_1}";
  $test->test_code_seg_2 = (isset($sort_keys[1]) ? $sort_keys[1] : NULL);

  if (isset($sort_keys[2]) && ((int)$sort_keys[2] > 0)) {
    $test->test_code_seg_3 = (int)$sort_keys[2];
    // strips leading zero, if it exists
    $sort_keys[2] = "{$test->test_code_seg_3}";
  }
  else {
    unset($sort_keys[2]);
  }
  if (isset($sort_keys[3]) && (strlen($sort_keys[3]))) {
    $test->test_code_seg_4 = $sort_keys[3];
  }
  else {
    unset($sort_keys[3]);
  }

  $test->test_code = implode('.', $sort_keys);


  // get array of selected engines
  $sel_engines = $form_state['values']['engines'];

  if ( $qtg_test_def_id ) {
    // edit
    $test->qtg_test_def_id = $qtg_test_def_id;
    $id = 'qtg_test_def_id';
    $bNew = False;
  }
  else {
    // new
    $id = array(); // id to be auto generated, do not provide one
    $bNew = True;
  }

  //--------- Save QTG Test Definition ------------

  // new or update record
  if ( False == drupal_write_record('qms_qtg_test_defs', $test, $id)) {
			$msg = "Oops!  Something went wrong saving the QTG Test record.";
			drupal_set_message(t($msg));
      return;
  }

  // process each engine - remove links to engines that were deselected
  // add links to engines that were selected
  foreach($sel_engines as $engine_type => $selected) {
    if ( $engine_type == $selected ) {
      // engine selected add or update it
      db_merge('qms_qtg_tests')
      ->key(array(
        'qtg_test_def_id' => $qtg_test_def_id,
        'engine_type' => $engine_type,
      ))->execute();
    }
    else {
      if ( $qtg_test_def_id ) {
        // engine not selected -
        // and test does not yet exist as a test event (checked in form validate)

        // remove test from assigned groups if editing an existing test
        db_delete('qms_qtg_groups_tests')
        ->where('qtg_test_id IN
                 (SELECT qtg_test_id FROM qms_qtg_tests
                  WHERE qtg_test_def_id = :tdid AND engine_type = :et)',
                 array(':tdid' => $qtg_test_def_id,
                       ':et' => $engine_type))
        ->execute();

        // remove test from assigned groups if editing an existing test
        db_delete('qms_qtg_tests')
        ->condition('qtg_test_def_id', $qtg_test_def_id)
        ->condition('engine_type', $engine_type)
        ->execute();

      }
    }
  }

  drupal_set_message(t("QTG Test successfully saved."));


  //---------- Routing -----------------------

  drupal_goto($goto_url);
}


/*
 *	qtg_test_delete_confirm()
 *
 *	Validate and Ask for confirmation before deleting record
 */

function qtg_test_delete_confirm($form, $form_state, $qtg_test_def_id = 0) {

  try {

    if ( !$qtg_test_def_id ) {
      drupal_set_message(
          t('Oops! Something went wrong. Invalid QTG Test Definition Id.'));
      drupal_goto($goto_url);
      return;
    }

    $goto_url = 'qmssettings/qtg/tests';
    $msg = '';

    $test = _get_qtg_test_definition($qtg_test_def_id);

    if ( Null == $test ) {
      drupal_set_message(t('Oops! Something went wrong. QTG Test not found.'));
      drupal_goto($goto_url);
      return;
    }


    $sql = "SELECT qtg_test_id FROM {qms_qtg_tests}
            WHERE qtg_test_def_id = :id LIMIT 1";
    $result = db_query($sql, array(':id' => $qtg_test_def_id));

    if ( $result->rowCount() ) {
      // cannot delete, linkage found
      $msg = "Unable to delete " . $test->test_code .
              ".  Test Definition is linked to Engines and Tests.  ";
      drupal_set_message(t($msg));
      drupal_goto($goto_url);
      return;
    }


    $form['qtg_test_def_id'] = array(
      '#type' => 'value',
      '#value' => $qtg_test_def_id,
    );

    $form['test_code'] = array(
      '#type' => 'value',
      '#value' => $test->test_code,
    );

    $form['test_desc'] = array(
      '#type' => 'value',
      '#value' => $test->test_desc,
    );


    $title = t('Delete QTG Test Definition') . '?';
    $question = t('Are you sure you want to delete?') .
                '<h2>' . $test->test_code . ': ' . $test->test_desc . '</h2><br />' .
                t('This action cannot be undone.');
    $goto_if_canceled = $goto_url;
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    // force this here to avoid a problem with routing if cancelled
    //$_GET['destination'] = $goto_if_canceled;

    return confirm_form($form, $title,	$goto_if_canceled, $question,
                        $yes_btn, $no_btn);
  }
  catch(Exception $e) {
    watchdog('sabreQMS', 'qtg_test_delete_confirm_submit()' . $e->getMessage(),
            array(), WATCHDOG_ERROR);
  }
}

/*
 *	qtg_test_delete_confirm_submit()
 *
 *	Submit after confirmation, delete the specified record
 */

function qtg_test_delete_confirm_submit($form, $form_state) {
  try {
    $goto_url = 'qmssettings/qtg/tests';

    if ( $form_state['values']['confirm']) {
      $qtg_test_def_id = $form_state['values']['qtg_test_def_id'];
      $test_code = $form_state['values']['test_code'];
      $test_desc = $form_state['values']['test_desc'];


      // delete from database
      $num_plans = db_delete('qms_qtg_test_defs')
                  ->condition('qtg_test_def_id', $qtg_test_def_id, '=')
                  ->execute();

      $msg = 'QTG Test, ' . $test_code . ', has been deleted.';

      drupal_set_message(t($msg));
    }

    drupal_goto($goto_url);
  }
  catch (Exception $e) {
    watchdog('sabreQMS', 'qtg_test_delete_confirm_submit()' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}






// NOT USING THIS -- Editing Schedules in the main display window, not as a separate form
// -----------------  QTG Test Schedule Form -----------------------
/*
 *    qtg_test_schedule_form()
 *
 *    Edit Test Plan Groups & Test associations
 *
 */
/*
function qtg_test_schedule_form($form, $form_state,
                                $qtg_test_plan_id = 0, $qtg_test_id = 0) {

  // setup for return routing
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'qmssettings/qtg/schedules';
	}


  if ( !$qtg_test_plan_id || !$qtg_test_id ) {
    $msg = "Oops!  Something went wrong. QTG Test Scheduling IDs are invalid.";
    drupal_set_message(t($msg));
    drupal_goto($goto_url);
    return;
  }

  $plan = _get_qtg_test_plan($qtg_test_plan_id);
  if ( !$plan ) {
    $msg = "Oops!  Something went wrong. QTG Test Plan not found.";
    drupal_set_message(t($msg));
    drupal_goto($goto_url);
    return;
  }

  // get all groups for the selected test plan
  $plan_group_list = _get_qtg_plan_groups($qtg_test_plan_id);

  if ( !count($plan_group_list) ) {
    $msg = "Oops!  Something went wrong. QTG Test Plan groups not found.";
    drupal_set_message(t($msg));
    drupal_goto($goto_url);
    return;
  }

  // get the test
  $test = _get_qtg_test($qtg_test_id);
  if ( !$test ) {
    $msg = "Oops!  Something went wrong. QTG Test not found.";
    drupal_set_message(t($msg));
    drupal_goto($goto_url);
    return;
  }

  // get currently assigned groups for this test
  // there may not be any
  $test_group_list = _get_qtg_test_groups($qtg_test_id, ($by_id = True));



  $form['test_plan'] = array(
    '#type' => 'item',
    '#title' => t('Test Plan'),
    '#markup' => $plan->plan_name,

  );
  $form['simulator'] = array(
    '#type' => 'item',
    '#title' => t('Simulator'),
    '#markup' => _st_format_sim_name($plan->sim_name, $plan->device_id_internal),

  );

  $form['test'] = array(
    '#type' => 'item',
    '#title' => t('Test'),
    '#markup' => $test->test_code . '<br />' .
                 $test->test_desc . '<br />' .
                 $test->engine_desc,

  );


  $group_opts = array();
  $group_vals = array();

  foreach($plan_group_list as $g) {
    $group_opts[$g->qtg_group_id] = $g->group_name . ' &nbsp;(' .
                                    t('Next: ') .
                                    _st_format_date($g->next_event, 'custom', 'm/d/Y') . ')';
  }

  foreach($test_group_list as $g) {
    $group_vals[] = $g->qtg_group_id;
  }

  $form['groups'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Groups'),
    '#options' => $group_opts,
    '#default_value' => $group_vals,
  );


  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#name' => 'submit',
    '#attributes' => array('class' => array('qms-btn-submit')),
  );

  $form['actions']['done'] = array(
    '#type' => 'button',
    '#value' => t('Done'),
    '#name' => 'done',
    '#attributes' => array('class' =>
                              array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' .
                              url($goto_url) . '"; return false;'),
  );


  return $form;
}
 * */



//-------------------- QTG Retrieval Functions ---------------------

/*
 *    _get_qtg_test_plans()
 *
 *    retrieves all test plans and their list of groups
 *
 */
function _get_qtg_test_plans($bGetGroups = False) {
  try{
    $plan_list = array();

    $sql = "SELECT p.qtg_test_plan_id, p.plan_name, p.simulator_id,
                   p.plan_frequency, s.sim_name, s.device_id_internal
            FROM {qms_qtg_test_plans} p, {qms_simulators} s
            WHERE p.active = 1
            AND   p.simulator_id = s.simulator_id";
    $result = db_query($sql);

    if ( $result->rowCount() ) {
      $plan_list = $result->fetchAll();

      if ( $bGetGroups ) {
        foreach($plan_list as $idx => $p) {
          $plan_list[$idx]->groups = _get_qtg_plan_groups($p->qtg_test_plan_id);
        }
      }
    }
    return $plan_list;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_plans() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_test_plans()



/*
 *    _get_qtg_test_plan()
 *
 */
function _get_qtg_test_plan($qtg_test_plan_id = 0) {
  try{
    $plan = (object) Null;

    if ( !$qtg_test_plan_id ) { return $plan; }

    $sql = "SELECT p.qtg_test_plan_id, p.plan_name, p.simulator_id,
                   p.plan_frequency, p.active, p.created_date, p.updated_date,
                   p.created_by_user, p.updated_by_user,
                   s.sim_name, s.device_id_internal
            FROM {qms_qtg_test_plans} p, {qms_simulators} s
            WHERE qtg_test_plan_id = :id
            AND   p.simulator_id = s.simulator_id";
    $result = db_query($sql, array(':id' => $qtg_test_plan_id));

    if ( $result->rowCount() ) {
      $plan = $result->fetchObject();
    }
    return $plan;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_plan() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_test_plan()


/*
 *    _get_qtg_plan_groups()
 *
 */
function _get_qtg_plan_groups($qtg_test_plan_id = 0) {
  try{
    $groups = array();

    if ( !$qtg_test_plan_id ) { return $groups; }

    $sql = "SELECT qtg_group_id, group_name, next_event
            FROM {qms_qtg_groups}
            WHERE qtg_test_plan_id = :id
            ORDER BY qtg_group_id ASC";
    $result = db_query($sql, array(':id' => $qtg_test_plan_id));

    if ( $result->rowCount() ) {
      $groups = $result->fetchAll();
    }
    return $groups;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_plan_groups() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_plan_groups()


/*
 *  _get_qtg_test_groups()
 *
 *  Get the list of groups to which this QTG test (test def & engine) is assigned
 *
 */
function _get_qtg_test_groups($qtg_test_id = 0) {
  try{
    $groups_assigned = array();

    if ( !$qtg_test_id ) { return $groups_assigned; }

    $sql = "SELECT gt.qtg_groups_tests_id, g.qtg_group_id, g.group_name, g.next_event
            FROM {qms_qtg_groups_tests} gt, {qms_qtg_groups} g
            WHERE gt.qtg_test_id = :id
            AND   gt.qtg_group_id = g.qtg_group_id
            ORDER BY g.qtg_group_id ASC";
    $result = db_query($sql, array(':id' => $qtg_test_id));

    if ( $result->rowCount() ) {
      // $groups_assigned = $result->fetchAll();
      foreach($result as $row) {
        $groups_assigned[$row->qtg_group_id] = 1;
      }

    }
    return $groups_assigned;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_groups() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_test_groups()


/*
 *  _get_qtg_groups_tests()
 *
 *  Get the list of tests linked to this group
 *
 */
function _get_qtg_groups_tests($qtg_group_id = 0) {
  try{
    $tests = array();

    if ( !$qtg_group_id ) { return $tests; }

    $sql = "SELECT qtg_test_id
            FROM {qms_qtg_groups_tests} gt
            WHERE qtg_group_id = :id
            ORDER BY qtg_test_id ASC";
    $result = db_query($sql, array(':id' => $qtg_group_id));

    if ( $result->rowCount() ) {
      $tests = $result->fetchAll();
    }
    return $tests;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_groups_tests() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_groups_tests()


/*
 *  _get_qtg_engines()
 *
 *  Retrieve all engines
 *
 */
function _get_qtg_engines() {
  try {

    $engine_list = array();

    // Get list of qtg engines
    $query = db_select('qms_qtg_engine_types', 'et')
              ->fields('et', array('engine_type', 'engine_code', 'engine_desc'))
              ->orderBy('engine_code', 'ASC');
    $result = $query->execute();
    if ( $result->rowCount() ) {
      $engine_list = $result->fetchAll();
    }
    return $engine_list;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_engines() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_engines()

/*
 *    _get_qtg_engine()
 *
 *  Retrieve a specific engine
 */
function _get_qtg_engine($engine_type = 0) {
  try{
    $engine = (object) Null;

    if ( !$engine_type ) { return $engine; }

    $sql = "SELECT engine_type, engine_code, engine_desc
            FROM {qms_qtg_engine_types}
            WHERE engine_type = :id";
    $result = db_query($sql, array(':id' => $engine_type));

    if ( $result->rowCount() ) {
      $engine = $result->fetchObject();
    }
    return $engine;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_engine() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_engine()


/*
 *    _get_qtg_test_engines()
 *
 */
function _get_qtg_test_engines($qtg_test_def_id = 0) {
  try{
    $engine_list = array();

    if ( !$qtg_test_def_id ) { return $engine_list; }

    $sql = "SELECT t.qtg_test_id, e.engine_type, e.engine_code
            FROM {qms_qtg_tests} t, {qms_qtg_engine_types} e
            WHERE t.qtg_test_def_id = :id
            AND t.engine_type = e.engine_type
            ORDER BY t.engine_type ASC";
    $result = db_query($sql, array(':id' => $qtg_test_def_id));

    if ( $result->rowCount() ) {
      $engine_list = $result->fetchAll();
    }
    return $engine_list;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_engines() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_test_engines()


/*
 *    _get_qtg_test()
 *
 */
function _get_qtg_test($qtg_test_id = 0) {
  try{
    $test = (object) Null;

    if ( !$qtg_test_id ) { return $test; }

    $sql = "SELECT t.qtg_test_id, t.qtg_test_def_id, td.test_code, td.test_desc,
                   e.engine_type, e.engine_code, e.engine_desc
            FROM {qms_qtg_tests} t, {qms_qtg_test_defs} td,
                 {qms_qtg_engine_types} e
            WHERE t.qtg_test_id = :id
            AND   t.qtg_test_def_id = td.qtg_test_def_id
            AND   t.engine_type = e.engine_type";
    $result = db_query($sql, array(':id' => $qtg_test_id));

    if ( $result->rowCount() ) {
      $test = $result->fetchObject();
    }
    return $test;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_test()


/*
 *    _get_qtg_test_definition()
 *
 */
function _get_qtg_test_definition($qtg_test_def_id = 0) {
  try{
    $test = (object) Null;

    if ( !$qtg_test_def_id ) { return $test; }

    $sql = "SELECT td.qtg_test_def_id, td.test_code, td.test_desc,
                   td.test_code_seg_1, td.test_code_seg_2, td.test_code_seg_3,
                   td.test_code_seg_4
            FROM {qms_qtg_test_defs} td
            WHERE td.qtg_test_def_id = :id";
    $result = db_query($sql, array(':id' => $qtg_test_def_id));

    if ( $result->rowCount() ) {
      $test = $result->fetchObject();
    }
    return $test;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_qtg_test_definition() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _get_qtg_test_definition()


/*
 *  _has_qtg_test_event()
 *
 *  IN:  $qtg_test_def_id
 *  IN:  $engine_type
 *  RETURN:  BOOL (True | False) if this combination is linked to QTG Test Events that have occurred.
 */
function _has_qtg_test_event($qtg_test_def_id, $engine_type) {
  try {
    $sql = "SELECT et.qtg_event_id
            FROM {qms_qtg_event_tests} et, {qms_qtg_tests} t
            WHERE et.qtg_test_id = t.qtg_test_id
            AND   t.qtg_test_def_id = :tdid
            AND   t.engine_type = :et
            LIMIT 1";

    $result = db_query($sql, array(':tdid' => $qtg_test_def_id,
                                   ':et' => $engine_type));

    if ( $result->rowCount() ) {
      // test event found for this test/engine
      return True;
    }
    // no test events found for this combination
    return False;
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_has_qtg_test_event() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
  }
}  // END ---- _has_qtg_test_event()



/*
 *	_is_test_code_unique($qtg_test_def_id, $test_code)
 *
 *	checks test code for uniqueness
 */
function _is_test_code_unique($qtg_test_def_id, $test_code)  {

	try{
		//if ( !count($test_code) ) { return False; }

		$sql = "SELECT qtg_test_def_id
            FROM {qms_qtg_test_defs}
						WHERE test_code = :tc
						AND   qtg_test_def_id != :id
						LIMIT 1";
		$result = db_query($sql, array(
                        ':tc' => $test_code,
                        ':id' => $qtg_test_def_id
                      ));
		if ( $result->rowCount() ) {
			return False;
		}

		return True;
	}
	catch (Exception $e) {
		watchdog('sabreQMS', '_is_test_code_unique() ' . $e->getMessage(),
              array(), WATCHDOG_ERROR);
	}
}

