<?php

function openid_server_authorized_sites($account) {
  // TODO: Can't we call this directly from the menu?
  return drupal_get_form('openid_server_authorized_sites_form', $account);
}

function openid_server_authorized_sites_form($form_state, $account) {
  $rps = openid_server_rp_load_all($account->uid);
  $form = array();
  if (is_array($rps) && count($rps) > 0) {
    $form['realms']['#tree'] = TRUE;
    for ($i = 0; $i < count($rps); $i++) {
      // We need to prefix the realm because it can be empty and #tree doesn't function
      // correctly with empty keys.
      $realm = 'realm-' . $rps[$i]->realm;
      $form['realms'][$realm]['realm'] = array(
              '#value' => $rps[$i]->realm);
      $form['realms'][$realm]['last_time'] = array(
              '#value' => format_date($rps[$i]->last_time));
      $form['realms'][$realm]['auto_release'] = array(
              '#type' => 'checkbox',
              '#default_value' => $rps[$i]->auto_release);
    }
    $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
  }
  else {
    $form['status'] = array('#value' => '<p>' . t('You have not sent information to any other sites yet.') . "</p>\n");
  }
  return $form;
}

function openid_server_authorized_sites_form_submit($form, &$form_state) {
  $uid = arg(1);
  foreach($form_state['values']['realms'] as $k => $v) {
    if(substr($k, 0, 6) != 'realm-') {
      continue;
    }
    $realm = substr($k, 6);
    if(!$realm) {
      $realm = ''; // When the realm is empty substr returns false
    }
    db_query("UPDATE {openid_server_relying_party} SET auto_release = %d WHERE uid = %d AND realm = '%s'",
              $form_state['values']['realms'][$k]['auto_release'], $uid, $realm);    
  }
}

function theme_openid_server_authorized_sites_form($form) {
  if(isset($form['status'])) {
    return drupal_render($form);
  }
  $header = array();
  $header[] = t('Realm');
  $header[] = t('Last time');
  $header[] = t('Auto release');
  $rows = array();
  foreach($form['realms'] as $k => $v) {
    if(substr($k, 0, 6) != 'realm-') {
      continue;
    }
    $row = array();
    $row[] = drupal_render($form['realms'][$k]['realm']);
    $row[] = drupal_render($form['realms'][$k]['last_time']);
    $row[] = drupal_render($form['realms'][$k]['auto_release']);
    $rows[] = $row;
  }
  $output = theme('table', $header, $rows);
  $output .= drupal_render($form);
  return $output;
}
