<?php
/**
 * Social Controller
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\ManagementBundle\Controller;

use DateTime;
use DOMDocument;
use DOMXPath;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

/**
 * Social Controller
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class SocialController extends Controller
{

    /**
     * Get RSS Items from VisualMedia feed
     *
     * @param int $limit Limit
     *
     * @return array Items
     */
    private function getRssItems($limit = 1)
    {
        if ($this->container->hasParameter('vm_rss_nieuws_link')) {
            $rss_nieuws_link = $this->container->getParameter('vm_rss_nieuws_link');
        } else {
            $rss_nieuws_link = 'http://www.visualmedia.nl/feed/rss/nieuws/?version=rss2&limit=%d';
        }

        $items = [];
        if (false !== ($rss = @file_get_contents(sprintf($rss_nieuws_link, $limit)))) {

            // Load XML
            $old_entity_load = libxml_disable_entity_loader(true);
            $dom = new DOMDocument('1.0', 'UTF-8');
            $dom->loadXML($rss);
            libxml_disable_entity_loader($old_entity_load);

            $xpath = new DOMXPath($dom);
            $item_nodes = $xpath->query('/rss/channel/item');

            foreach($item_nodes as $item_node) {
                /* @var \DOMElement $item_node */

                $item = [
                    'type' => 'rss'
                ];
                if (null !== ($feed_link= $xpath->query('/rss/channel/link')->item(0))) {
                    $item['feed_link'] = $feed_link->textContent;
                }
                if (null !== ($title = $xpath->query('./title', $item_node)->item(0))) {
                    $item['title'] = $title->textContent;
                }
                if (null !== ($link = $xpath->query('./link', $item_node)->item(0))) {
                    $item['link'] = $link->textContent;
                }
                if (null !== ($description = $xpath->query('./description', $item_node)->item(0))) {
                    $item['description'] = $description->textContent;
                }
                if (null !== ($pub_date = $xpath->query('./pubDate', $item_node)->item(0))) {
                    $item['date'] = new DateTime($pub_date->textContent);
                }
                if (null !== ($enclosure = $xpath->query('./enclosure[@type="image/jpeg"]', $item_node)->item(0))) {
                    $item['image'] = $enclosure->getAttribute('url');
                } elseif (null !== ($enclosure = $xpath->query('./enclosure[@type="image/png"]', $item_node)->item(0))) {
                    $item['image'] = $enclosure->getAttribute('url');
                } elseif (null !== ($enclosure = $xpath->query('./enclosure[@type="image/gif"]', $item_node)->item(0))) {
                    $item['image'] = $enclosure->getAttribute('url');
                }

                $items[] = $item;


            }
        }

        return $items;
    }

    /**
     * Get Facebook Items
     * 
     * @param int $limit Limit
     * 
     * @returna array Items
     */
    private function getFacebookItems($limit = 1)
    {
        if ($this->container->hasParameter('vm_facebook_link')) {
            $facebook_link = $this->container->getParameter('vm_facebook_link');
        } else {
            $facebook_link = 'http://api.visualmedia.nl/facebook/facebook.php?format=json&limit=%d';
        }

        $items_raw = json_decode(@file_get_contents(sprintf($facebook_link, $limit)));

        if (!is_array($items_raw)) {
            return [];
        }

        $items = [];
        foreach($items_raw as $item_raw) {
            $item = [
                'type' => 'facebook'
            ];
            if (!empty($item_raw->feed_link)) {
                $item['feed_link'] = $item_raw->feed_link;
            }
            if (!empty($item_raw->link)) {
                $item['link'] = $item_raw->link;
            }
            if (!empty($item_raw->title)) {
                $item['title'] = $item_raw->title;
            }
            if (!empty($item_raw->message)) {
                $item['description'] = $item_raw->message;
            }
            if (!empty($item_raw->updated)) {
                $item['date'] = new DateTime($item_raw->updated);
            }
            if (!empty($item_raw->image_url) AND $item_raw->image_width > 300) {
                $item['image'] = $item_raw->image_url;
            }
            $items[] = $item;
        }

        return $items;
    }

    /**
     * Get Twitter Items
     *
     * @param int $limit Limit
     *
     * @returna array Items
     */
    private function getTwitterItems($limit = 1)
    {
        if ($this->container->hasParameter('vm_twitter_link')) {
            $twitter_link = $this->container->getParameter('vm_twitter_link');
        } else {
            $twitter_link = 'http://api.visualmedia.nl/twitter/twitter.php?format=json&limit=%d';
        }

        $items_raw = json_decode(@file_get_contents(sprintf($twitter_link, $limit)));

        if (!is_array($items_raw)) {
            return [];
        }

        $items = [];
        foreach($items_raw as $item_raw) {
            $item = [
                'type' => 'twitter'
            ];
            if (!empty($item_raw->feed_link)) {
                $item['feed_link'] = $item_raw->feed_link;
            }
            if (!empty($item_raw->link)) {
                $item['link'] = $item_raw->link;
            }
            if (!empty($item_raw->title)) {
                $item['title'] = $item_raw->title;
            }
            if (!empty($item_raw->message)) {
                $item['description'] = $item_raw->message;
            }
            if (!empty($item_raw->updated)) {
                $item['date'] = new DateTime($item_raw->updated);
            }
            if (!empty($item_raw->image_url) AND $item_raw->image_width > 300) {
                $item['image'] = $item_raw->image_url;
            }
            $items[] = $item;
        }

        return $items;
    }

    /**
     * Render News Feed (Mix of Facebook/RSS/Twitter)
     *
     * @return Response Response
     */
    public function newsFeedAction()
    {
        $items = [];
        
        $items = array_merge($items, $this->getFacebookItems(1));
        $items = array_merge($items, $this->getTwitterItems(1));
        $items = array_merge($items, $this->getRssItems(3 - min(3, max(0, count($items)))));

        usort($items, function($a, $b) {
            if (!isset($a['date'])) {
                return 1;
            } else if (!isset($b['date'])) {
                return -1;
            } else if ($a['date'] > $b['date']) {
                return -1;
            } else if ($a['date'] < $b['date']) {
                return 1;
            } else {
                return 0;
            }
        });

        return $this->render('VisualMManagementBundle:Social:newsFeed.html.twig', [
            'items' => $items
        ]);

    }

    
}