<?php

class PBReusableModel_YouTube extends CI_Model {

	const PODCASTS = 'taw_feed_podcasts';
	const WRITING = 'taw_feed_writing';
	const PARTNERS = 'auth_partners';
	const VIDEOS = 'taw_feed_videos';
	const NOTIFICATIONS_LOG = 'taw_notifications_log';

	private $nextPage = 0;
	private $nextPageToken = '';

    function __construct() {
        parent::__construct();
		$this->load->helper('date');
        // $this->load->model('PBReusableModel_Analytics','analytics');
    }


    public function updateOnDuplicate($table, $data ) {
        if (empty($table) || empty($data)) return false;
        $duplicate_data = array();
        foreach($data AS $key => $value) {
            $duplicate_data[] = sprintf("%s='%s'", $key, $value);
        }
        $sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));
        $this->db->query($sql);
		if($this->db->insert_id()) {
			echo "insert_id ".$this->db->insert_id();
			if($table == 'taw_feed_videos') {
				echo "table ".$table;
				$this->load->database();
		        $this->db->select('*');
		        $this->db->from(self::NOTIFICATIONS_LOG);
				$this->db->limit(1);
				$this->db->where('post_id =',$data['post_id']);
		        $query = $this->db->get();
		        if($query->num_rows() == 0) {
					echo "should send ".$data['post_id'];
					$this->notifications->sendNewVideoNotificationToUsers($data['post_id']);
				}
			}
		}
        return $this->db->insert_id();
    }

	/* VIDEOS START *****************************************************************/

	public function insertVideoFeedContentFromYouTube($video) {
		$article_array = array();
		$article_array['post_id'] = $video->snippet->resourceId->videoId;
		$article_array['title'] = addslashes($video->snippet->title);
		$article_array['content'] = addslashes($video->snippet->description);
		$article_array['excerpt'] = addslashes($video->snippet->title);
		$article_array['created_date'] = $video->snippet->publishedAt;
		$article_array['modified_date'] = $video->snippet->publishedAt;
		$article_array['cost'] = 0;
		$article_array['video_url'] = addslashes($video->id);
		$article_array['thumbnail_image'] = addslashes($video->snippet->thumbnails->default->url);
		$article_array['medium_image'] = addslashes($video->snippet->thumbnails->medium->url);
		$article_array['large_image'] = addslashes($video->snippet->thumbnails->high->url);
		$article_array['type'] = 'youtube';
		$this->updateOnDuplicate(self::VIDEOS,$article_array);
		return true;
	}

    public function getVideosJSONFromYouTube($page) {
		$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=5&playlistId=UUc5C5dNupCMbyutNatfBujQ&key=AIzaSyDA45he0ahYKrGyiE-oz6gpK_jDQidd3nk&pageToken=".$page;

        $curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_URL => $url,
		));
		return curl_exec($curl);
    }

    public function getVideosFeedFromYoutube($page) {

        $json = $this->getVideosJSONFromYouTube($this->nextPageToken);
        $json = json_decode($json);
		// echo $json->posts;
		// return true;
		if($json->items) {
			foreach($json->items as $video) {
				$this->insertVideoFeedContentFromYouTube($video);
			}
            // if(isset($json->nextPageToken)) {
			// 	$this->nextPageToken = $json->nextPageToken;
			// 	$this->nextPage = $this->nextPage+1;
			// 	$this->getVideosFeedFromYoutube($this->nextPageToken);
            // } else {
                return true;
            // }
		} else {
            return true;
        }
    }


}
