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

// https://github.com/500px/api-documentation

class Intense_500px {
	public $consumer_key, $endpoints, $photos;

	// there is also an original size that my vary from this
	// image sizes 5, 1600, 2048 are undocumented sizes
	public $native_sizes = array(
		"1" => array( 'width' => 70, 'height' => 70 ),
		"2" => array( 'width' => 140, 'height' => 140 ),
		"3" => array( 'width' => 280, 'height' => 280 ),
		"4" => array( 'width' => 900, 'height' => 600 ),
		"5" => array( 'width' => 1170, 'height' => 780 ),
		"1600" => array( 'width' => 1600, 'height' => 1067 ),
		"2048" => array( 'width' => 2048, 'height' => 1365 ),
	);

	function Intense_500px(  ) {
		global $intense_visions_options;
		$this->consumer_key = ( isset( $intense_visions_options['intense_px500_consumer_key'] ) ? $intense_visions_options['intense_px500_consumer_key'] : null );

		$this->endpoints = array(
			'user'    => 'https://api.500px.com/v1/photos?consumer_key=%1$s&username=%2$s&feature=user&image_size[]=1&image_size[]=2&image_size[]=3&image_size[]=4&image_size[]=1600&image_size[]=2048&page=%3$s'
		);
		$this->photos = array();
	}

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

		$page++; //500px pages are 1 based

		if ( $userid ) {
			$api_url  = sprintf( $this->endpoints['user'], $this->consumer_key, $userid, $page );
		}

		$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'] );

			foreach ( $data->photos as $item ) {
				$photo = new Intense_Photo( "500px", "http://500px.com/photo/" . $item->id, $item->name, $item->description );

				foreach ( $item->images as $image ) {
					$width = $this->native_sizes[ strval( $image->size ) ]['width'];
					$height = $this->native_sizes[ strval( $image->size ) ]['height'];

					$photo->add_size(
						$image->size,
						$width,
						$height,
						$image->url );
				}

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

		return $this->photos;
	}
}
