<?php
// $Id

// author : Alex McFadyen (openlyconnectec.com) - http://drupal.org/user/195063
// @todo update settings so they can be per field not just global. 

define('IMAGE_NCCK_DEFAULT_FLICKR_SET_CLASS', 'flickr-set');
define('IMAGE_NCCK_DEFAULT_FLICKR_SET_HEADER', '<a href="!url" target="_blank">Flickr Set : @name, showing @number of @total images</a>');
define('IMAGE_NCCK_DEFAULT_FLICKR_SET_LIMIT', 10);

include_once('flickr.inc');
/**
 * hook image_ncck_PROVIDER_info
 * this returns information relevant to a specific 3rd party video provider
 * @return
 *   an array of strings requested by various admin and other forms
 *   'name' => the translated name of the provider
 *   'url' => the url to the main page for the provider
 *   'settings_description' => a description of the provider that will be posted in the admin settings form
 *   'supported_features' => an array of rows describing the state of certain supported features by the provider.
 *      These will be rendered in a table, with the columns being 'Feature', 'Supported', 'Notes'.
 */

function image_ncck_flickr_sets_info() {
	echo('CALLED');
  $name = t('Flickr Sets');
  return array(
    'provider' => 'flickr_sets',
    'name' => $name,
    'url' => IMAGE_NCCK_FLICKR_MAIN_URL,
    'settings_description' => t('These settings specifically affect images displayed from !flickr.', array('!flickr' => l($name, IMAGE_NCCK_FLICKR_MAIN_URL, array('target' => '_blank')), '!api' => l(t('API'), IMAGE_NCCK_FLICKR_API_INFO, array('target' => '_blank'))))
  );
}

/**
 * hook image_ncck_PROVIDER_settings
 * this should return a subform to be added to the image_ncck_settings() admin settings page.
 * note that a form field will already be provided, at $form['PROVIDER'] (such as $form['flickr'])
 * so if you want specific provider settings within that field, you can add the elements to that form field.
 */
function image_ncck_flickr_sets_settings() {
  $form['flickr_set']['image_ncck_flickr_set_limit'] = array(
    '#type' => 'textfield',
    '#title' => t('Flickr Sets limit'),
    '#default_value' => variable_get('image_ncck_flickr_set_limit', IMAGE_NCCK_DEFAULT_FLICKR_SET_LIMIT),
    '#description' => t("The maxamum number of results to return from flickr for each set."),
  );
  $form['flickr_set']['image_ncck_flickr_set_class'] = array(
    '#type' => 'textfield',
    '#title' => t('Flickr Sets CSS class'),
    '#default_value' => variable_get('image_ncck_flickr_set_class', IMAGE_NCCK_DEFAULT_FLICKR_SET_CLASS),
    '#description' => t("The class or classes to be applied to the wrapper around the Flickr set's results."),
  );
  $form['flickr_set']['image_ncck_flickr_set_header'] = array(
    '#type' => 'textfield',
    '#title' => t('Flickr Sets header'),
    '#default_value' => variable_get('image_ncck_flickr_set_header', IMAGE_NCCK_DEFAULT_FLICKR_SET_HEADER),
    '#description' => t("The text placed above the selection of images, this text can use several tokens<br/>
    <ul><li>!url : The url back to the set on flickr's website</li>
    <li>@name : The name of the set</li>
    <li>@total : The total number of images in the set</li>
    <li>@number : The number of images currently being displayed from the set</li>
    <li>@description : The description of the set, from flickr</li></ul>")
  );
  return $form;
}

/**
 * hook image_ncck_PROVIDER_extract($embed)
 * Strips out the ID of the resource from a url or embed code.
 *  @param $embed
 *    the string containing the contents to check
 *  @return
 *    a string containing the id or a array with a regex pattern in it.
 */
function image_ncck_flickr_sets_extract($embed = '') {
  //http://www.flickr.com/photos/9382875@N05/sets/2238059970
  return array('@flickr\.com/photos/[^/]*/sets/(\d+)@i');
}

/**
 * hook image_ncck_PROVIDER_data($code)
 * returns an array of data about the item
 *  @param $field
 *  	a array with the form api details of the field calling
 *  @param $item
 *    a array containing the item to get data for
 *  @return
 *    a array of data about the item
 */
function image_ncck_flickr_sets_data($field, $item) {
  $images = image_ncck_flickr_sets_getSet($item['value']);
  
  if (preg_match('@flickr\.com/photos/([^/]*)@i', $item['embed'], $matches)) {
  	$owner = $matches[1];
  }
  
  $data = array();
  foreach ($images['#set'] as $image) {
    $tags = array();
    if (is_array($image['#tags'])) {
      foreach ($image['#tags'] as $tag) {
        $tags[] = $tag['raw'];
      }
    }
    
    $data[] = array(
      'owner' => $owner,
      'title' => $image['#title'],
    	'description' => $image['#description'],
      'tags' => $tags
    );
  }
  
  return $data;
}



/**
 *  This allows flickr photosets to be collected
 * @todo update the image_ncck_flickr_request/request_xml to get tags correctly
 */
function image_ncck_flickr_sets_getSet($id, $limit = -1, $page = 0) {
	if ($limit == -1) $limit = variable_get('image_ncck_flickr_set_limit', IMAGE_NCCK_DEFAULT_FLICKR_SET_LIMIT);
  $images = array();

  // http://www.flickr.com/photos/nikkiana/sets/72157601948647678/
  if (is_numeric($id)) {
    $page ++;  // flickr starts current page at 1
    $args = array('photoset_id' => $id);
    if ($limit) {
      $args['per_page'] = $limit;
    }
    $args['page'] = $page;
    //print_r($args);
    $xml = image_ncck_flickr_request('flickr.photosets.getPhotos', $args);
    //print_r($xml);
    $images['#pages'] = $xml['photoset']['pages'];
    $images['#page'] = $xml['photoset']['page'] - 1;
    $images['#total'] = $xml['photoset']['total'];
    $images['#per_page'] = $xml['photoset']['per_page'];
    $images['#set'] = array();
    foreach ($xml['photoset']['photo'] as $photo) {
      $data = image_ncck_flickr_data(NULL, array('value' => $photo['id']));
      $images['#set'][] = array(
        '#code' => $photo['id'],
        '#title' => $photo['title'],
        '#link' => image_ncck_flickr_embedded_link($photo['id'], $xml['photoset']['owner']),
        '#thumb' => image_ncck_flickr_image_url($photo['id'], 100, 100, NULL, NULL, NULL),
        '#body' => $images['description'],
        '#tags' => $images['tags'],
      );
    }
  }
  return $images;
}

/**
 * hook image_ncck_PROVIDER_embedded_link($code)
 * returns a link to view the content at the provider's site
 *  @param $code
 *    the string containing the content to watch
 *  @return
 *    a string containing the URL to view the video at the original provider's site
 */
function image_ncck_flickr_sets_embedded_link($code, $data = array()) {
  return image_ncck_flickr_embedded_link($code, $data);
}

/**
 *  implement image_ncck_PROVIDER_image_title
 *
 *  @param $code
 *    the code of the image
 *  @param $data
 *    any stored data for the image, which may already have the title
 *  @return
 *    the title as the 3rd party provider knows it, if accessible to us. otherwise, ''
 */
function image_ncck_flickr_sets_image_title($code, $data) {
  return image_ncck_flickr_image_title($code, $data);
}


/**
 *  implement image_ncck_PROVIDER_image_url
 *
 *  @param $code
 *    the code of the image
 *  @param $data
 *    any stored data for the image, which may already have the title
 *  @return
 *    the url directly to the image to display
 */
function image_ncck_flickr_sets_image_url($code, $width, $height, $formatter = NULL, $field = NULL, $item = NULL, $node = NULL) {
  return image_ncck_flickr_image_url($code, $width, $height, $formatter, $field, $item, $node);
}



/**
 *  implement image_ncck_PROVIDER_image_display
 *
 *  @return
 *    formatted image(s)
 */
function image_ncck_flickr_sets_image_display($field, $item, $formatter, $node, $code, $width, $height, $link) {
	$output = '<div class="'.variable_get('image_ncck_flickr_set_class', IMAGE_NCCK_DEFAULT_FLICKR_SET_CLASS).'">';
	$images = image_ncck_flickr_sets_getSet($item['value']);
  
  if (preg_match('@flickr\.com/photos/([^/]*)@i', $item['embed'], $matches)) {
  	$owner = $matches[1];
  }
  
  $xml = image_ncck_flickr_request('flickr.photosets.getInfo', array('photoset_id'=>$item['value']));
  
  $number = count($images['#set']);
  
  $output .= t(variable_get('image_ncck_flickr_set_header', IMAGE_NCCK_DEFAULT_FLICKR_SET_HEADER), 
				  				array( 
				  					'!url' => $item['embed'],
				  					'@name' => $xml['photoset']['title']['_content'],
				  					'@total' => $xml['photoset']['photos'],
				  					'@number' => $number,
				  					'@description' => strip_tags($xml['photoset']['description']['_content'])
				  			 ));
  
  foreach ($images['#set'] as $image) {
  	$this_link = $link;
    $tags = array();
    if (is_array($image['#tags'])) {
      foreach ($image['#tags'] as $tag) {
        $tags[] = $tag['raw'];
      }
    }
    
    if ($this_link == IMAGE_NCCK_LINK_CONTENT) {
      $this_link = 'node/' . $node->nid;
    }
    else if ($link == IMAGE_NCCK_LINK_PROVIDER) {
      $this_link = image_ncck_flickr_sets_embedded_link($image['#code'], array('owner'=>$owner));
    }
    else {
      $this_link = NULL;
    }
		$title = image_ncck_flickr_sets_image_title($image['#code'], array('title'=>$image['#title']));
		$output .= theme('image_ncck_image', $field, $item, $formatter, $node, $image['#code'], $width, $height, $title, $this_link);

  }
  
  return $output.'</div>';
  			
  
}