<?php

class BaseController extends Controller {

	/**
	 * Setup the layout used by the controller.
	 *
	 * @return void
	 */
	protected function setupLayout()
	{
		if ( ! is_null($this->layout)) {
			$this->layout = View::make($this->layout);
		}
	}



	protected function respondSuccess($msg)
	{
		$response = array(
			'error'   => 0,
			'msg' => $msg
		);
		echo json_encode($response);
	}



	protected function respondSuccessData($data)
	{
		$response = array(
			'error' => 0,
			'data'  => $data
		);
		echo json_encode($response);
	}



	protected function respondError($msg)
	{
		$response = array(
			'error' => 1,
			'msg'  => $msg
		);
		echo json_encode($response);
	}



	public function crone($response = false)
	{
		$response = (boolean) $response;
		$nets = (object) ColumnsModel::where('state','=',1)->get()->toArray();
		$newStatusesNum = array();

		foreach($nets as $net)
		{
			$net['hashtag'] = str_replace('+AND+',',',$net['hashtag']);
			$net['callBack'] = $net['social_network'] == 1 ? 'getTweets' : 'getInstagrams';

			$newStatusesNum[] = $this->{ $net['callBack'] }($net['hashtag'], $net['id'], $response);
		}

		if($response)
		{
			return Response::json($newStatusesNum);
		}
	}



	/**
	 * Get tweets from twitter API by hashtag.
	 *
	 * @param $hashtag
	 * @param $idColumn
	 * @return array
	 */

	protected function getTweets($hashtag,$idColumn, $response = false)
	{
		$tweets		= array();
		$parameters	= array(
			'q'					=> '#'.$hashtag,
			'result_type'		=> 'mixed',
			'count'				=> '1000',
			'rpp'				=> '500',
			'include_entities'	=> 1
		);
		$result = array();

		$rawTweets = Twitter::getSearch($parameters);
		$rawTweets = !empty($rawTweets->statuses) ? $rawTweets->statuses : array();


		for($i=0; count($rawTweets) > $i; $i++)
		{

			$tweets[$i]['remote_id']		= $rawTweets[$i]->id;
			$tweets[$i]['text']				= $rawTweets[$i]->text;
			$tweets[$i]['likes']			= $rawTweets[$i]->favorite_count;
			$tweets[$i]['id_user']			= $rawTweets[$i]->user->id;
			$tweets[$i]['username']			= $rawTweets[$i]->user->screen_name;
			$tweets[$i]['profile_img']		= $rawTweets[$i]->user->profile_image_url;
			$tweets[$i]['media']			= NULL;
			$tweets[$i]['social_network']	= 1;
			$tweets[$i]['remote_timing']	= date('Y-m-d H:i:s', strtotime($rawTweets[$i]->created_at));
			$tweets[$i]['id_column']		= $idColumn;

			if(isset($rawTweets[$i]->entities->media[0]->media_url))
			{
				$tweets[$i]['media'] = $rawTweets[$i]->entities->media[0]->media_url;
			}

			$newStatus = $this->_saveStatuses($tweets);
			if( !empty($newStatus) )
			{
				$result[] = $newStatus;
			}
		}

		if( $response )
		{
			return array(
				'id' => $idColumn,
				'num'=>count($tweets),
				'statuses' => $result
			);
		}
	}



	/**
	 * Get photos and statuses from Instagram.
	 *
	 * @param $hashtag
	 * @param $idColumn
	 * @return array
	 */

	protected function getInstagrams($hashtag,$idColumn, $response = false)
	{
		require_once app_path().'/lib/instagram.class.php';

		$instagrams	= array();
		$settings	= Config::get('app.socialNetwork.instagram');
		$result		= array();

		$instagram	= new Instagram($settings);
		$rawInstagrams = $instagram->getTagMedia($hashtag, 7);

		$rawInstagrams = !empty($rawInstagrams->data) ? $rawInstagrams->data : null;

		if(!is_null($rawInstagrams)) {
			for($i=0; count($rawInstagrams) > $i; $i++) {
				if (!empty($rawInstagrams[$i]->caption->from->username)) {
					$instagrams[$i]['remote_id']		= $rawInstagrams[$i]->caption->id;
					$instagrams[$i]['text']				= $rawInstagrams[$i]->caption->text;
					$instagrams[$i]['likes']			= $rawInstagrams[$i]->likes->count;
					$instagrams[$i]['id_user']			= $rawInstagrams[$i]->caption->from->id;
					$instagrams[$i]['username']			= $rawInstagrams[$i]->caption->from->username;
					$instagrams[$i]['profile_img']		= $rawInstagrams[$i]->caption->from->profile_picture;
					$instagrams[$i]['media']			= $rawInstagrams[$i]->images->standard_resolution->url;
					$instagrams[$i]['remote_timing']	= date('Y-m-d H:i:s', $rawInstagrams[$i]->caption->created_time);
					$instagrams[$i]['social_network']	= 2;
					$instagrams[$i]['id_column']		= $idColumn;
				}
				$newStatus = $this->_saveStatuses($instagrams);
				if( !empty($newStatus) )
				{
					$result[] = $newStatus;
				}
			}
		}

		if( $response )
		{
			return array(
				'id' => $idColumn,
				'num' => count($instagrams),
				'statuses' => $result
			);
		}
	}



	/**
	 * Saves a collected statuses to a the database.
	 *
	 * @param $statuses
	 * @return array
	 */
	private function _saveStatuses($statuses)
	{
		$cm = new StatusesModel();
		$result = array();

		foreach($statuses as $status)
		{
			if($cm->where('remote_id', '=', $status['remote_id'])
				->where('social_network', '=', $status['social_network'])
				->count() == 0)
			{

				foreach($status as $key => $val)
				{
					$cm->$key = $val;
				}

				$cm->save();

				$result[] = $cm->toArray();
			}
		}

		return $result;
	}



	public function pd($arr)
	{
		echo "<pre>";
		print_r($arr);
		echo "</pre>";
		die();
	}
}
