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

// http://www.deviantart.com/developers/rss

class Intense_DeviantART {
	public $endpoints, $photos;

	function Intense_DeviantART(  ) {
		$this->photos = array();
	}

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

		$offset = $page * $pagesize;

		if ( $userid ) {
			$api_url  = 'http://backend.deviantart.com/rss.xml?type=deviation&q=by%3A' . $userid . '+sort%3Atime+meta%3Aall+offset%3A' . $offset . '+length%3A' . $pagesize;
		}

		$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 = simplexml_load_string( $response['body'] );

			foreach ( $data->channel->item as $item ) {
				$values = json_decode( json_encode( $item ), TRUE );
				$link = $values['link'];
				$title = $values['title'];
				$description = ( isset( $values['description'][0] ) ? $values['description'][0] : '' );
				$photo = new Intense_Photo( "DeviantART", $link, $title, $description );

				$namespaces = $item->getNameSpaces( true );
				$media = $item->children( $namespaces['media'] );

				if ( $media->thumbnail && $media->thumbnail[0]->Attributes() ) {
					foreach ( $media->thumbnail as $thumbnail ) {
						$thumb = json_decode( json_encode( $thumbnail->Attributes() ), TRUE );
						$height = $thumb['@attributes']['height'];
						$width = $thumb['@attributes']['width'];
						$url = $thumb['@attributes']['url'];

						$photo->add_size(
							$width . "X" . $height,
							$width,
							$height,
							$url );
					}
				}

				if ( $media->content && $media->content->attributes() ) {
					$content = json_decode( json_encode( $media->content->attributes() ), TRUE );

					if ( $content['@attributes']['medium'] == "image" ) {
						$height = $content['@attributes']['height'];
						$width = $content['@attributes']['width'];
						$url = $content['@attributes']['url'];

						$photo->add_size(
							$width . "X" . $height,
							$width,
							$height,
							$url );
					}
				}

				if ( count( $photo->sizes ) > 0 ) {
					$this->photos[] = $photo;
				}
			}
		}

		return $this->photos;
	}
}
