<?php
/**
 * @package    pixelcms_articles
 *
 * @author     christophf <your@email.com>
 * @copyright  A copyright
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       http://your.url.com
 */

use Joomla\CMS\MVC\View\HtmlView;

defined('_JEXEC') or die;

/**
 * Pixelcms_articles view.
 *
 * @package  pixelcms_articles
 * @since    1.0
 */
class Pixelcms_articlesViewPixelcms_galleries extends HtmlView
{
    public $item_id;
    public $gallery;
    public $cms_url;
    public $alias;
    protected $classSuffix = 'gallery__body';
    /**
     * @var extendedRegistry
     * @since version
     */
    public $params;
    public $options;
    public $hasVimeoPlayer = false;
    public $hasYoutubePlayer = false;
    public $hasFacebookPlayer = false;
    public $hasVideoPlayer = false;
    protected $is_module = false;

    protected function _setPath($type, $path)
    {
        $component = 'com_pixelcms_articles';
        $app = JFactory::getApplication();

        // Clear out the prior search dirs
        $this->_path[$type] = array();

        // Actually add the user-specified directories
        $this->_addPath($type, $path);

        // Always add the fallback directories as last resort
        switch (strtolower($type))
        {
            case 'template':
                // Set the alternative template search dir
                if (isset($app))
                {
                    $component = preg_replace('/[^A-Z0-9_\.-]/i', '', $component);
                    $fallback = JPATH_THEMES . '/' . $app->getTemplate() . '/html/' . $component . '/' . $this->getName();
                    $this->_addPath('template', $fallback);
                }
                break;
        }
    }

    public function compileClassList(array $classList): string
    {
        $classList = array_filter($classList);
        $classList = array_map(function($className, $classModifier) {
            return (is_numeric($className)) ? "cms_article--$classModifier" : "cms_article--$className-$classModifier";
            }, array_keys($classList), $classList);

        return implode(' ', $classList);
    }

    public function getThumbnail($image, int $size = 500, bool $cropped = true): string
    {
        $url = (is_string($image)) ? $image : $image->url;

        if (!is_string($image) && $image->is_animated_gif) {
            return $url;
        }

        return preg_replace('/^(?:\/)?((?!http)(?:(?!thumb).)*)(?:\.\d+)?\.(jpe?g|png|gif)/', ($cropped) ? "$1.$size-cropped.$2" : "$1.$size.$2", $url);
    }

    public function getVideoUrl($video)
    {
        $this->hasVideoPlayer = true;
        if ($video->vendor_id === 2) {
            $this->hasVimeoPlayer = true;
            return "https://player.vimeo.com/video/$video->video_id?title=0&byline=0&portrait=0";
        } else if ($video->vendor_id === 3) {
            $uid = bin2hex(random_bytes(3));
            $this->hasFacebookPlayer = true;
            return "<div class=\"facebook_player fb-video\" id='fb-v-$video->video_id-$uid' data-id='fb-v-$video->video_id-$uid' data-href=\"$video->url\" data-allowfullscreen=\"true\" data-width=\"720\"></div>";
        }
        $this->hasYoutubePlayer = true;
        return "<iframe class='youtube_player' src=\"https://www.youtube-nocookie.com/embed/$video->video_id?rel=0&showinfo=0&enablejsapi=1\" width=\"1280\" height=\"720\" frameborder=\"0\" allowfullscreen></iframe>";
    }

    public function displayGallery($gallery, $showDescription = false)
    {
        $html = [];

        $thumbSize = $this->params->get('pixelcms_images_thumb_size', 500);
        $previewSize = $this->params->get('pixelcms_images_preview_size', 1600);

        $cssClass = ($showDescription) ? 'gallery__item__thumb' : 'gallery__item';

        foreach ($gallery->images as $image) {
            $thumb = $this->getThumbnail($image, $thumbSize);
	        $preview = $this->getThumbnail($image, $previewSize, false);

            $elm = ["<a class='js-img $cssClass $cssClass--image img' data-title='$image->title'  href='{$this->params->get('pixel_cms_url')}/$preview' style='background-image: url({$this->params->get('pixel_cms_url')}/$thumb)'></a>"];

            if ($showDescription) {
                $this->renderGalleryItemDesc($elm, $image);
            }

            $html[] = implode('', $elm);
        }
        foreach ($gallery->videos as $video) {
            $elm = ["<a class='$cssClass $cssClass--video' style='background-image: url($video->thumb)'></a>"];

            if ($showDescription) {
                $this->renderGalleryItemDesc($elm, $video);
            }

            $html[] = implode('', $elm);
        }

        if ($limit = $this->params->get('limit', null)) {
            array_splice($html, 0, $limit);
        }

        return implode('', $html);
    }

    private function renderGalleryItemDesc(array &$elm, $item): void
    {
        $preElm = '<div class="gallery__item gallery__item--desc">';

        $elm[] = '<div class="gallery__item__meta">';
        $elm[] = "<span class='gallery__item__meta__title'>$item->title</span>";
        $elm[] = "<span class='gallery__item__meta__desc'>$item->description</span>";
        $elm[] = "</div>";


        array_unshift($elm, $preElm);
        $elm[] = "</div>";
    }

    public function attachPlayerScripts()
    {
        if (!$this->hasVideoPlayer) {
            return "";
        }
        $html = [];
        $script = ['var play_class = "video--playing";'];
        if ($this->hasVimeoPlayer) {
            $html[] = "<script src='https://player.vimeo.com/api/player.js'></script>";
            $script[] = '
                [].slice.call(document.querySelectorAll(".vimeo_player")).forEach(function (el) {
                    var player = new Vimeo.Player(el);
                
                    player.on(\'play\', function () {
                        el.parentElement.classList.add(play_class);
                    });
                    player.on(\'pause\', function () {
                        el.parentElement.classList.remove(play_class);
                    });
                });
            ';
        }
        if ($this->hasYoutubePlayer) {
            $html[] = "<script src='https://www.youtube.com/iframe_api'></script>";
            $script[] = '
                function onYouTubeIframeAPIReady() {
                    [].slice.call(document.querySelectorAll(".youtube_player")).forEach(function (el) {
                        var player = new YT.Player(el, {
                            events: {
                                onStateChange: function onStateChange(event) {
                                    if (event.data === YT.PlayerState.PLAYING) {
                                        el.parentElement.classList.add(play_class);
                                    } else if (event.data === YT.PlayerState.PAUSED) {
                                        el.parentElement.classList.remove(play_class);
                                    }
                                }
                            }
                        });
                    });
                }
            ';
        }
        if ($this->hasFacebookPlayer) {
            $html[] = "<script src='https://connect.facebook.net/de_DE/sdk.js'></script>";
            $script[] = '
                function fbAsyncInit() {
                    FB.init({
                        appId      : \'922247001285262\',
                        xfbml      : true,
                        version    : \'v2.11\'
                    });

                    FB.Event.subscribe(\'xfbml.ready\', function(msg) {
                        console.log(msg.instance, msg);
                        if (msg.type === \'video\') {
                            msg.instance.subscribe(\'startedPlaying\', function(e) {
                                document.getElementById(msg.id).parentElement.classList.add(play_class);
                            });
                            msg.instance.subscribe(\'paused\', function(e) {
                                document.getElementById(msg.id).parentElement.classList.remove(play_class);
                            });
                            msg.instance.subscribe(\'finishedPlaying\', function(e) {
                                document.getElementById(msg.id).parentElement.classList.remove(play_class);
                            });
                        }
                    });
                };
            ';
        }
        $script = array_map(function($value) {
            return preg_replace('/[\s]{2,}/', '', $value);
        }, $script);
        $html[] = '<script>' . implode("", $script) . '</script>';
        return implode("\n", $html);
    }

    public function getContainerClass(): string
    {
        $viewName = $this->getName();

        $classList[] = "$viewName-wrapper";
        if ($this->params->get('is_module')) {
            $classList[] = 'mod_cms-wrapper';
            $classList[] = "$viewName-mod-wrapper";
        }
        $classList[] = $this->classSuffix;

        return implode(' ', $classList);
    }

	function display($tpl = null)
	{
		// Assign data to the view

        $this->gallery = $this->get('Gallery');

		$this->params = $this->get('state')->get('params');

        $tpl = ($this->params->has('articleId')) ? null : 'listing';

        $document = JFactory::getDocument();
        $document->addStyleSheet(JURI::base(true) . '/media/com_pixelcms_articles/css/fonts.css', [
            'version' => md5_file(JPATH_BASE . '/media/com_pixelcms_articles/css/fonts.css'),
        ]);
        $document->addStyleSheet(JURI::base(true) . '/media/com_pixelcms_articles/css/style.css', [
            'version' => md5_file(JPATH_BASE . '/media/com_pixelcms_articles/css/style.css'),
        ]);
        $document->addScript(JURI::base(true) . '/media/com_pixelcms_articles/js/script.js', [
            'version' => md5_file(JPATH_BASE . '/media/com_pixelcms_articles/js/script.js'),
        ]);

		// Display the view
		parent::display($tpl);
	}
}
