<?php
/*
	DevSaver Web Framework
	Copyright (c) 2013-2016 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com				
*/


class CSocialMediaWidgetInstagram extends CWidget {

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $meta = array(
		"type"	=> "4",
		"name"	=> "Instagram Feed",
	);

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Render($widget) {

		global $base;


		$data = $this->updateFeed($widget);


		if (!is_array($photos = $data["graphql"]["user"]["edge_owner_to_timeline_media"]["edges"])) {
			return "";
		}

		$cnt = 1;
		foreach ($photos as $key => $val) {
			$media[] = array(
				"title"		=> $val["node"]["edge_media_to_caption"]["edges"][0]["node"]["text"],
				"image"		=> $val["node"]["thumbnail_src"],
				"likes"		=> $val["node"]["edge_liked_by"]["count"],
				"comments"	=> $val["node"]["edge_media_to_comment"]["count"],
			);			

			$cnt++;

			if ($cnt > $widget["settings"]["set_items"]) {
				break;
			}
		}


		global $base;

		return $this->tpl->blockReplace(
			"Main" , 
			array(
				"images"	=> $base->html->Table(
					$this->tpl , 
					"",
					$media
				),

				"class"	=> $this->tpl->blockreplace($widget["settings"]["set_carousel"] ? "Carousel" :"List"),

			),
			$widget["settings"],
			$widget
		);

	
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function updateFeed($widget) {

		$file = "./upload/tmp/widget-" . $widget["widget_id"] . ".json";
		$expire = time() - 10 * 60;

		if (file_exists($file) && (filectime($file) > $expire) ) {
		} else {
			//reload the feed
			$feed = CHttp::newInstance()
				->get("https://www.instagram.com/{$widget[settings][set_user]}/?__a=1")
				->raw();

			//save in tmp
			CFile::Save($file , $feed );
		}

		return 	json_decode(CFile::Get($file) , true);

	}
	
}



?>