<?php
require_once 'Intense-photo.php';

//https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol

class Intense_Picasa {
	public $endpoints, $photos;

	//add a c to the native size and you get the cropped version.
	public $native_sizes = "32,48,64,72,94,104,110,128,144,150,160,200,220,288,320,400,512,576,640,720,800,912,1024,1152,1280,1440,1600";

	function Intense_Picasa(  ) {
		$this->endpoints = array(
			'user'    => 'https://picasaweb.google.com/data/feed/api/user/%1$s?fields=entry(title,summary,link[@rel=\'alternate\'],media:group(media:description,media:thumbnail))&kind=photo&max-results=%2$s&alt=json&start-index=%3$s&thumbsize=%4$s',
			'album' => 'https://picasaweb.google.com/data/feed/api/user/%1$s/albumid/%2$s?fields=entry(title,summary,link[@rel=\'alternate\'],media:group(media:description,media:thumbnail))&alt=json&max-results=%3$s&start-index=%4$s&thumbsize=%5$s',
			'tag'    => 'https://picasaweb.google.com/data/feed/api/user/%1$s?fields=entry(title,summary,link[@rel=\'alternate\'],media:group(media:description,media:thumbnail))&kind=tag&tag=%2$s&max-results=%3$s&alt=json&start-index=%4$s&thumbsize=%5$s',
		);

		$this->photos = array();
	}

	function get_photos( $userid, $album, $page, $pagesize ) {
		$api_url = null;

		$thumbnail_sizes = explode( ",", $this->native_sizes );

		// foreach ($thumbnail_sizes as $key => $value) {
		// 	$thumbnail_sizes[] = $value . "c";
		// }

		// usort( $thumbnail_sizes, 'strnatcmp' );

		$thumbnail_sizes = join( ",", $thumbnail_sizes );

		$page++; //google is 1 indexed
		
		if ( $album ) {
			$api_url  = sprintf( $this->endpoints['album'], $userid, $album, $pagesize, $page, $thumbnail_sizes );
		// } else if ( $tag ) {
		// 	$api_url  = sprintf( $this->endpoints['tag'], $userid, $tag, $pagesize, $page, $thumbnail_sizes );
		} else if ( $userid ) {
			$api_url  = sprintf( $this->endpoints['user'], $userid, $pagesize, $page, $thumbnail_sizes );
		}

		$response = wp_remote_get( $api_url,
			array(
				'sslverify' => apply_filters( 'https_local_ssl_verify', false )
			)
		);

		if ( !is_wp_error( $response ) && $response['response']['code'] < 400 && $response['response']['code'] >= 200 ) {
			$data = json_decode( $response['body'], true );

			if ( isset( $data['feed']['entry'] )) {
				foreach ( $data['feed']['entry'] as $item ) {
					if ( isset( $item['media$group']['media$thumbnail'] )) {
						$photo = new Intense_Photo( "picasa", $item['link'][0]['href'], $item['title']['$t'], $item['summary']['$t'] );
					
						$thumbnails = $item['media$group']['media$thumbnail'];
					
						foreach ($thumbnails as $thumb) {					
							$photo->add_size( 
								$thumb['width'] . "X" . $thumb['height'], 
								$thumb['width'], 
								$thumb['height'], 
								$thumb['url'] );
						}
						

						$this->photos[] = $photo;
					}
				}
			}
		} 

		return $this->photos;
	}
}

