<?php
require_once(drupal_get_path('module', 'flickrrippr') . '/flickrrippr.inc');

/**
 * Implementation of hook_perm().
 */
function flickrrippr_permission() {
  return array(
    'Configure own blogged flickr stream' => array(
      'title' => 'Configure own blogged flickr stream',
      'description ' => ''
    ),
    'Administer global flickr api settings' => array(
      'title' => 'Administer global flickr api settings',
      'description ' => ''
    ),
    'use flickr secret importer' => array(
      'title' => 'Use flickr secret importer',
      'description ' => ''
    )
  );
}


/**
 * Register View API information. This is required for your module to have
 * its include files loaded; for example, when implementing
 * flickrrippr_views_default_views().
 *
 * @return
 *   An array with the following possible keys:
 *   - api:  (required) The version of the Views API the module implements.
 *   - path: (optional) If includes are stored somewhere other than within
 *       the root module directory or a subdirectory called includes, specify
 *       its path here.
 */
function flickrrippr_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'flickrrippr') .'/views/',
  );
}


/**
 * Implementation of hook_menu().
 */
function flickrrippr_menu() {
  GLOBAL $user;
  $items = array();
  $items['flickr/secret'] = array(
     'page callback' => 'drupal_get_form',
     'page arguments' => array('flickrrippr_secret_form'),
     'access arguments' => array('use flickr secret importer'),
     'file' => 'flickrrippr.secret.inc',
     'type' => MENU_NORMAL_ITEM,
     'title' => 'Flickr Secret Import',
  );
  $items['admin/content/flickrrippr'] = array(
    'title' => 'Flickr Rippr',
    'description' => 'View users, and force re-read from flickr.com',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'flickrrippr_admin',
    'access arguments' => array('Administer global flickr api settings'),
    'file' => 'flickrrippr.admin.inc',
  );

  $items['admin/content/flickrrippr/fetch'] = array(
    'title' => 'Fetch',
    'type' => MENU_CALLBACK,
    'page callback' => 'flickrrippr_admin_fetch',
    'page arguments' => array(4),
    'access arguments' => array('Administer global flickr api settings'),
    'file' => 'flickrrippr.admin.inc',
  );

  $items['admin/content/flickrrippr/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_CALLBACK,
    'page callback' => 'flickrrippr_admin_edit',
    'page argument' => array(4, 5),
    'access arguments' => array('Administer global flickr api settings'),
    'file' => 'flickrrippr.admin.inc',
  );

  //configure a user's account with their flickr username
  $items['user/%/flickrrippr'] = array(
    'title' => 'Flickr Rippr',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'flickrrippr_user_settings',
    'page arguments' => array(1),
    'access arguments' => array('Configure own blogged flickr stream'),
    'file' => 'flickrrippr.user.inc',
  );
  $items['user/%/flickrrippr/add'] = array(
    'title' => 'add',
    'type' => MENU_CALLBACK,
    'page callback' => 'flickrrippr_user_add_account',
    'page arguments' => array(1),
    'access arguments' => array('Configure own blogged flickr stream'),
    'file' => 'flickrrippr.user.inc',
  );
  $items['user/%/flickrrippr/edit/%'] = array(
    'title' => 'edit',
    'type' => MENU_CALLBACK,
    'page callback' => 'flickrrippr_user_edit_account',
    'page arguments' => array(1, 4),
    'access arguments' => array('Configure own blogged flickr stream'),
    'file' => 'flickrrippr.user.inc',
  );

  $items['user/%/flickrrippr/view/%'] = array(
    'title' => 'View Photos',
    'type' => MENU_CALLBACK,
    'page callback' => 'flickrrippr_user_view_photos',
    'page arguments' => array(1, 4),
    'access arguments' => array('access content'),
    'file' => 'flickrrippr.user.inc',
  );

  $items['user/%/flickrrippr/delete/%'] = array(
    'title' => 'delete',
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('flickrrippr_user_delete_account', 1, 4),
    'access arguments' => array('Configure own blogged flickr stream'),
    'type' => MENU_CALLBACK,
  );


  $items['node/%/flickrrefresh'] = array(
    'title' => 'Re-fetch from Flickr',
    'page callback' => 'flickrrippr_node_refresh',
    'page arguments' => array(1),
    'access callback' => 'flickrrippr_node_refresh_permission',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/flickr'] = array(
    'title' => 'Flickr',
    'page callback' => 'flickrrippr_admin_menu_page',
    'access arguments' => array('access administration pages'),
  );
  $items['admin/flickr/flickrrippr'] = array(
    'title' => 'Flickr Rippr settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('flickrrippr_admin_settings_form'),
    'access arguments' => array('Administer global flickr api settings'),
    'description' => 'Configure the settings for Flickr Rippr.',
    'file' => 'flickrrippr.admin.inc',
  );
  return $items;
}

function flickrrippr_node_refresh_permission($nid) {
  $node = node_load($nid);
  if($node->type == 'flickrrippr_photo') {
    return true;
  }
}

function flickrrippr_admin_menu_page() {
    return '';
}

function flickrrippr_user_delete_account($form, $uid, $flickrid) {
  $form = array();
  $form['uid'] = array('#type' => 'hidden', '#value' => $uid);
  $form['flickrid'] = array('#type' => 'hidden', '#value' => $flickrid);

  $form['message'] = array(
    '#type' => 'markup',
    '#value' => '<p>'. t('Are you sure you want to delete this account?') . '</p>'
  );

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

  return $form;
}

function flickrrippr_user_delete_account_submit($form, &$form_state) {
  $uid = $form_state['values']['uid'];
  $flickrid = $form_state['values']['flickrid'];
  db_query("DELETE FROM {flickrusers} WHERE uid=%d AND flickrid='%s'", $uid, $flickrid);
  drupal_goto('user/'. $uid .'/flickrrippr');
}

function flickrrippr_node_refresh_perm($nid) {
  //check if this has a photo id
  $photo_id = flickrrippr_node_get_photoid($nid);

  if (!$photo_id) {
    return FALSE;
  }

  $node = node_load(array('nid' => $nid));
  return node_access('update', $node);
}




/**
 * Get the details of a flickr user from the database
 */
function flickrrippr_get_flickruser($uid, $flickrid) {
  $cached = db_select('flickrusers', 'fu')
    ->fields('fu')
    ->condition('uid', $uid)
    ->condition('flickrid', $flickrid)
    ->addTag('FlickrRippr')
    ->execute()
    ->fetch();
    
  if ($cached) {
//     drupal_set_message(print_r($cached, 1));
    return $cached;
  }
  drupal_set_message("fetching info on $flickrid");

  $flickruser = new StdClass();
  $flickruser->flickrid = $flickrid;
  $flickruser->uid = 0;
  include_once(drupal_get_path('module', 'flickrrippr').  '/flickrrippr.user.inc');
  flickrrippr_fetch_user_info_and_save($flickruser, true);
 
}

/**
 * Loading of the node
 */
function flickrrippr_node_load($nodes, $types) {
  $photos = db_select('flickrphotos', 'p')
    ->fields('p')
    ->condition('nid', array_keys($nodes))
    ->execute();
  foreach($photos as $p) {
    $nodes[$p->nid]->flickr_photo = $p;


  }

//   drupal_set_message(print_r($nodes, 1));
}

/**
 * Re-fetch a photo from flickr
 */
function flickrrippr_node_refresh($nid) {

  $photo_id = flickrrippr_node_get_photoid($nid);

  if (!$photo_id) {
    drupal_set_message(t('Photo not found. This should never happen'), 'error');
  }
  else {
    flickrrippr_makenode($photo_id);
  }

  drupal_goto('node/' . $nid);
}




/**
 * Called by cron, this check for new photos for each user
 * This function will recurse, reading futher back into the flickr stream
 * until it finds a photo it already has saved as a node
 */
function flickrrippr_check_latest_for_flickruser($user_id, $pagenum = 1) {
 //fetches defails from our database
  $flickrusers =  flickrrippr_get_flickr_accounts($user_id);

  foreach ($flickrusers as $fu) {
    flickrrippr_fetch_latest($fu);
  }
}



/**
 * Get the latest from flickr.com for one user
 */
function flickrrippr_fetch_latest($flickruser, $force_now=FALSE) {
  if($force_now) {
    drupal_set_message(t("Forcing refetch now, not queuing"));
  }
  if ($force_now) {
//   , drupal_get_path('module', 'flickrrippr') .'/flickrrippr.user.inc');
    flickrrippr_fetch_user_info_and_save($flickruser);
    
  }

  $num_photos = variable_get('flickrrippr_num_per_fetch', 100);

 //search flickr for latest photos from that user.
  $flickr = flickrapi_phpFlickr();
  if (!$flickr) {
    drupal_set_message(t("Unable to query flickr.com"), 'error');
    watchdog('flickrrippr', 'Unable to query flickr.com');
    return FALSE;
  }

  $query = array(
    'user_id' => $flickruser->flickrid,
    'per_page' => $num_photos,
  );

  if ($flickruser->tag) {
    $query['tags'] = check_plain($flickruser->tag);
  }

  $photos = $flickr->photos_search($query);
  $num_photos = 0;
  if (is_array($photos['photo'])) {
    foreach ($photos['photo'] as $p) {
        //hack to get around job_queue restricting descriptions to 255 chars
        flickrrippr_makenode($p['id']);
        $num_photos++;
      }
//     }
  }

  drupal_set_message(t('!count photos queued for import.', array('!count' => $num_photos)));

}

/**
 * Helper function, returns the flickr_id for a flickr username.
 */
function flickrrippr_flickruser($username) {
  $flickr = @flickrapi_phpFlickr();
  if (!$flickr) {
    drupal_set_message(t("Unable to query flickr.com"), 'error');
    return $output;
  }
  $fuser = $flickr->people_findByUsername($username);

  if (!$fuser['id']) {
    drupal_set_message(t('%username is not known by flickr.com', array('%username' => $username)), 'error');
    return;
  }

  db_update('flickrusers')
    ->fields(array('flickrid' => $fuser['id']))
    ->condition('flickrusername', $username) 
    ->execute();
  return $fuser['id'];
}

/**
 * Implementation of hook_cron().
 */
function flickrrippr_cron() {
  //get missing flickrids
//   flickrrippr_add_missing_flickrids();

  $accounts = db_select('flickrusers')
    ->fields('flickrusers')
   ->execute();
  foreach($accounts as $fuser) {
    flickrrippr_check_latest_for_flickruser($fuser->uid);
  }
}

function flickrrippr_image($node, $size) {
  if(!$node) {
    return;
  }
  $src = flickrrippr_path($node, $size);
  return theme('image',
    array(
      'path' => $src,
      'alt' => $node->title,
      'title' => $node->title,
      'getsize' => FALSE
      )
  );
}

function flickrrippr_user_avatar($a) {
  if (isset($a->flickravatar) && !empty($a->flickravatar) && !preg_match('!farm0!', $a->flickravatar)) {
  
    //make image
    $avatar = theme('image', array(
      'path' => check_plain($a->flickravatar),
      'alt' => check_plain($a->flickrusername),
      'title' => check_plain($a->flickrusername),
      'getsize' => FALSE
      )
    );
    //and put link around it
    $avatar = l($avatar, $a->flickrphotosurl, array('html' => TRUE));
  }
  else {
    $avatar = '';
  }
  return $avatar;
}

function flickrrippr_user_fetch_now($a, $uid, $flickrid, $dest='') {
  $form = array();
  $form['flickrid'] = array('#type' => 'hidden', '#value' => $flickrid);
  $form['uid'] = array('#type' => 'hidden', '#value' => $uid);
  $form['dest'] = array('#type' => 'hidden', '#value' => $dest);
  $form['fetch'] = array('#type' => 'submit', '#value' => t('Fetch now'));
  return $form;
}


/**
 * Manually fetch all the latest for a user
 */
function flickrrippr_user_fetch_now_submit($form, &$form_state) {
//   $flickrid = $fv['values']['flickrid'];
  $flickrid = $_POST['flickrid'];
  $uid = $_POST['uid'];
  $dest = $_POST['dest'];

  if (!$dest) {
    $dest = 'user/'. $uid .'/flickrrippr';
  }
  //get user
  $fuser = flickrrippr_get_flickruser($uid, $flickrid);
  if (!$fuser) {
    drupal_set_message(t('Flickr user (uid=%uid, flickrid=%flickrid) not found in our database', array('%uid' => $uid, '%flickrid' => $flickrid)), 'error');
    return;
  }

  drupal_set_message(t("Fetching latest for %flickrid", array("%flickrid" => $flickrid)));


  //and fetch
  flickrrippr_fetch_latest($fuser, TRUE);

  drupal_goto(check_plain($dest));
}

/**
 * Used when attempting to edit a flickrphoto node.
 */
function flickrrippr_form(&$node) {
  $form = array();
  //TODO add instructions on edit the photo on flickr.com

  return $form;
}

function flickrrippr_node_info() {
  return array(
    'flickrrippr_photo' => array(
      'name' => t('Flickr Rippr Photo'),
      'module' => 'flickrrippr',
      'description' => t("Photos imported from a user's flickr stream"),
      'has_body' => FALSE,
      )
    );
}

/**
 * Instead of displaying a damaged node, display a form for deleting it
 */
function flickrrippr_failed_form($form, $node) {
  $form = array();
  $form['message'] = array(
    '#type' => 'markup',
    '#value' => t('Photo no longer available on flickr.com, do you want to delete?') . ' ',
  );
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $node->nid,
  );
  $form['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Yes, Delete from this website'),
  );
  return $form;
}

function flickrrippr_failed_form_submit($form, $fv) {
  $nid = $fv['values']['nid'];
  node_delete($nid);
//   drupal_set_message(t('Flickr photo delete from this website'));
  drupal_goto('<front>');

}

function theme_flickrrippr_photo($node, $size) {
}

function flickrrippr_node_view($node, $view_mode, $langcode) {

  if (empty($node->flickr_photo)) {
    drupal_set_message(t('No photo info attached'), 'error');
    watchdog('flickrrippr', 'Node has no photo info. !link', array('!link' => l($node->title, 'node/'. $node->nid)), WATCHDOG_ERROR);
    return $node;
  }

  $photo = (array)$node->flickr_photo;
  

  if ($photo['failed'] == 1) {
    if (node_access('delete', $node)) {
      drupal_set_message(t("Failed to find flickr photo info for !link", array('!link' => l($node->title, 'node/' . $node->nid))), 'error');
//       $node->content['delete'] = array(
//         '#value' => drupal_get_form('flickrrippr_failed_form', $node),
//         '#weight' => -10,
//       );
    }
    return;
  }
//   drupal_set_message($view_mode);

  switch($view_mode) {
    default:
    case 'full':
    $size = variable_get('flickrrippr_page_size', 'z');
    $link = $photo['photopage'];
    break;
    case 'teaser':
    $size = variable_get('flickrrippr_teaser_size', 't');
    $link = 'node/'. $node->nid;
    break;
  }
  

  //get the image, using theme()

  $jpeg_path = flickrrippr_path($node, $size);

  $image = l(flickrrippr_image($node, $size), $link, array('html' => TRUE));
  $node->content['flickr_photo_'.$size] = array(
    '#weight' => 0,
    '#markup' => '<div class="flickrrippr_photo">' . $image . '</div>',
//     '#theme' => 'theme_flickrrippr_photo',
  );



  $markup_trust = variable_get('flickrrippr_markup_trust', FALSE);

  $node->content['body'] = array(
    '#markup' => '<div class="flickrrippr_description">'. nl2br($markup_trust ? $photo['description'] : check_plain($photo['description']))  .'</div>', //decode then encode
    '#weight' => 5
  );


  $owner = flickrrippr_get_flickruser($node->uid, $node->flickr_photo->owner_nsid);
  //stdClass Object ( [uid] => 0 [tag] => [date_field] => [flickrid] => 14565961@N05 [flickrusername] => cooleyjj [flickrispro] => 1 [flickrphotosurl] => http://www.flickr.com/photos/j_cooley/ [flickrprofileurl] => http://www.flickr.com/people/j_cooley/ [flickravatar] => http://farm3.static.flickr.com/2051/buddyicons/14565961@N05.jpg [flickrrealname] => [flickrpath_alias] => j_cooley [flickrlocation] => [flickrmobileurl] => http://m.flickr.com/photostream.gne?id=14560621 )
  


  $owner_name = !empty($owner->flickrrealname) ? $owner->flickrrealname : $owner->flickrusername;
  $list[] = t('Photo owner: !realname', array('!realname' => l(check_plain($owner_name), $owner->flickrphotosurl)));

  $list[] = t('Date Taken: @date_taken', array('@date_taken' => format_date(strtotime($node->flickr_photo->date_taken), 'short')));
  $list[] = t('Date Uploaded: @date_posted', array('@date_posted' => format_date($node->flickr_photo->date_posted, 'short')));
  $list[] = t('Views: @views', array('@views' => numbeR_format($node->flickr_photo->views)));
  
  
  $node->content['details'] = array(
    '#weight' => 0,
    '#markup' => '<div class="flickrphoto_details">' . theme('item_list', array('items' => $list)) .'</div>'
  );

//   $node->links['photopage'] = array(
//       'title' => t('Flickr Photo Page'),
//       'href' => $node->flickr_photo->photopage,
//     );


}


function flickrrippr_node_form(&$form_state, $node) {
}

function flickrrippr_node_delete($node) {
  db_delete('flickrphotos')
    ->condition('nid', array($node->nid));
  drupal_set_message(t("Flickr Rippr photo %title deleted.", array('%title' => $node->title)));
}


/**
 * All the different sizes flickr have
 */
function _flickr_rippr_jpeg_sizes() {
  return array(
//     'sq' => t('Square (75 x 75)'),
    't'  => t('Thumbnail (100 x 75)'),
    's'  => t('Small (240 x 180)'),
    'm'  => t('Medium 500 (500 x 375)'),
    'z'  => t('Medium 640 (640 x 480)'),
    'b'  => t('Large (1024 x 768)'),
    'o'  => t('Original (2592 x 1944)')
  );
}


function flickrrippr_date_options() {
  return array(
//     'dateuploaded' => t('Uploaded to Flickr'),
    'date_taken' => t('Photo was taken'),
    'lastfetched' => t('Last fetched from flickr'),
    'date_posted'  => t('Posted to Flickr'),
    'date_lastupdate' => t('Last update on Flickr'),
  );
  
}
