<?php
/**
 * @file
 * Core functionality for the Selfi.
 */

/**
 * Implements hook_help().
 */
function selfi_help($path, $arg) {
  switch ($path) {
    case "admin/help#selfi":
      $output = '<p>' . t('Selfi module allows you to take selfie which you can save as profile picture.') . '</p>';
      $output .= '<p>' . t('It take picture from your browser using webcam internally connected or external also.') . '</p>';
      $output .= '<p>' . t('It provide facility to save user picture in public folder.<p> We are also working on providing facility to the user for their previous clicks collection as a gallery.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_menu().
 */
function selfi_menu() {
  $items['admin/config/media/selfi'] = array(
    'title' => 'Selfi configuration',
    'description' => 'Settings for selfi',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('selfi_webrtc_settings'),
    'access arguments' => array('administer selfi'),
    'file' => 'selfi.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );

  $items['selfi/upload-pic'] = array(
    'title' => 'Upload profile picture',
    'page callback' => 'selfi_upload_pic',
    'access arguments' => array('take selfi'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function selfi_permission() {
  return array(
    'administer selfi' => array(
      'title' => t('Administer selfi'),
      'description' => t('Perform administration tasks for selfi module.'),
    ),
    'take selfi' => array(
      'title' => t('Take Selfi'),
      'description' => t('Allow users to take selfi'),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function selfi_theme() {
  return array(
    'selfi' => array(
      'render element' => 'element',
      'variables' => array(
        'user' => NULL,
        'video_width' => check_plain(variable_get('selfi_preview_width', 300)),
        'video_height' => check_plain(variable_get('selfi_preview_height', 200)),
      ),
      'template' => 'selfi',
    ),
  );
}

/**
 * Upload image to public folder.
 */
function selfi_upload_pic() {
  global $user;
  $status = array();
  // Check the token to make sure it is a valid request.
  if (!empty($_POST['selfi_token']) && drupal_valid_token($_POST['selfi_token'], 'selfi-upload') &&!empty($_POST['img_data'])) {
    $uri = 'public://';
    $wrapper = file_stream_wrapper_get_instance_by_uri($uri);
    $upload_dir = $wrapper->realpath() . '/' . variable_get('selfi_path', 'selfi_clicks') . '/';
    $img = $_POST['img_data'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $filename = $user->name . '-' . REQUEST_TIME . '.png';
    $file = $upload_dir . $filename;
    $success = file_put_contents($file, $data);
    $status = array(
      'status'  => ($success) ? array(
        'msg'   => t('File saved successfully.'),
        'value' => 1,
        'file'  => $filename,
      ) : array('msg' => t('Problem while saving the file. Please check directory write permission'), 'value' => 0),
    );
  }
  else {
    $status = array(
      'status'  => FALSE,
    );
  }
  print drupal_json_encode($status);
  drupal_exit();
}


/**
 * Implements hook_form_FORM_ID_alter().
 */
function selfi_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (user_access('take selfi')) {
    $settings = array(
      'width' => check_plain(variable_get('selfi_preview_width', 300)),
      'height' => check_plain(variable_get('selfi_preview_height', 200)),
      'selfiToken' => drupal_get_token('selfi-upload'),
    );
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'selfi') . '/js/selfi.js',
      array(
        'data' => array('selfi' => $settings),
        'type' => 'setting',
      ),
    );

    $form['#attached']['css'] = array(
      drupal_get_path('module', 'selfi') . '/css/selfi.css',
    );

    $form['picture']['upload_type'] = array(
      '#type' => 'radios',
      '#default_value' => 'upload_picture',
      '#weight' => -1,
      '#options' => array(
        'upload_picture' => t('Upload picture'),
        'take_picture' => t('Take picture'),
      ),
    );

    $form['picture']['picture_upload']['#states'] = array(
      'visible' => array(
        'input[name="upload_type"]' => array(
          'value' => 'upload_picture'),
      ),
    );
    $form['picture']['take_picture'] = array(
      '#type' => 'item',
      '#markup' => theme('selfi', array('account' => $user)),
      '#states' => array(
        'visible' => array('input[name="upload_type"]' => array('value' => 'take_picture')),
      ),
    );

    $form['picture']['selfi'] = array(
      '#type' => 'hidden',
      '#attributes' => array(
        'id' => 'selfi-data',
      ),
    );
    $form['#submit'][] = 'selfi_user_profile_submit';
  }
}

/**
 * Custom submit handler for user profile form submit.
 *
 * @see selfi_form_alter
 */
function selfi_user_profile_submit(&$form, &$form_state) {
  global $user;
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
    'file_validate_extensions' => array('png'),
  );
  if ($form_state['values']['selfi'] && $form_state['values']['upload_type'] == 'take_picture') {
    $filename = $form_state['values']['selfi'];
    $picture_directory = 'public://' . variable_get('selfi_path', 'selfi_clicks');
    $uri = file_stream_wrapper_uri_normalize($picture_directory . '/' . $filename);
    // Create a file object.
    $file = new stdClass();
    $file->uid = $user->uid;
    $file->filename = $filename;
    $file->uri = $uri;
    $file->filemime = 'image/png';
    $file->filesize = filesize($uri);
    $file->status = 1;

    // Check for errors.
    $errors = file_validate($file, $validators);
    if (!empty($errors)) {
      if (count($errors) > 1) {
        $message = theme('item_list', array('items' => $errors));
      }
      else {
        $message = ' ' . array_pop($errors);
      }
      form_set_error('picture', $message);
      return FALSE;
    }
    // If there are no errors record this file in the database.
    $file_obj = file_save($file);
    // Save user profile.
    $account = user_load($user->uid);
    $old_pic = $account->picture;
    $edit = array(
      'picture' => $file_obj,
    );
    $acc_save = user_save($account, $edit);
    file_usage_add($file_obj, 'user', 'user', $account->uid);
    // Delete old picture if changes were saved in user account.
    if ($acc_save && !empty($old_pic)) {
      file_usage_delete($old_pic, 'user', 'user', $account->uid);
      file_delete($old_pic);
    }
  }
}
