<?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_news extends HtmlView
{
    public $params;
    protected $news;
    protected $category;
    protected $is_module = false;

    static $attachments = [
        'galleries' => 'gallery',
        'workers' => 'worker',
        'pdfs' => 'pdf',
        'files' => 'file',
        'videos' => 'video',
        'images' => 'image',
        'locations' => 'location',
        'departments' => 'department',
    ];

    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;
        }
    }

    private function displayFile($file)
    {
        return "<a class='pdf' target='_blank' href='{$this->params->get('pixel_cms_url')}/storage/$file->file'><span class='pdf__title'>$file->title</span></a>";
    }

    private function displayWorker($worker)
    {
        //$html[] =  "<pre>". print_r($worker, true) ."</pre>";
        if ($worker->image) {
            $html[] = "<div class='worker__image' style='background-image: url({$this->params->get('pixel_cms_url')}{$worker->image->url})'></div>";
        }
        $html[] = "<h4 class='worker__title'>$worker->first_name $worker->last_name</h4>";
        if (isset($worker->role)) {
            $html[] = "<span class=\"worker__role\">$worker->role</span>";
        }
        $html[] = "<ul class=\"worker__contact\">";
        if ($worker->email) {
            $html[] = "<li><a href=\"mailto:$worker->email\"><i class=\"pixelcms-icons\">email</i><span>$worker->email</span></a></li>";
        }
        if ($worker->tel) {
            $html[] = "<li><a href=\"tel:$worker->tel\"><i class=\"pixelcms-icons\">phone</i><span>$worker->tel</span></a></li>";
        }
        if ($worker->mobile) {
            $html[] = "<li><a href=\"tel:$worker->mobile\"><i class=\"pixelcms-icons\">phone_android</i><span>$worker->mobile</span></a></li>";
        }

        $html[] =  "</ul>";
        return implode("\n", $html);
    }

    private function displayDepartment($department) {
        $html[] = '';
        foreach ($department->workers as $worker) {
            $html[] = "<div class='worker worker--col-4'>";
            $html[] = $this->displayWorker($worker);
            $html[] = "</div>";
        }
        return implode("\n", $html);
    }

    private function displayPdf($pdf)
    {
        return "<a class='pdf' target='_blank' href='{$this->params->get('pixel_cms_url')}/$this->alias/pdfs/$pdf->alias'><img class='pdf__image' src='{$this->params->get('pixel_cms_url')}/$pdf->url'><span class='pdf__title'>$pdf->title</span></a>";
    }

    private function displayVideo($video)
    {
        if ($video->vendor_id === 2) {
            $this->hasVimeoPlayer = true;
            return "<iframe class='vimeo_player' src=\"https://player.vimeo.com/video/$video->video_id?title=0&byline=0&portrait=0\" width=\"1280\" height=\"720\" frameborder=\"0\" allowfullscreen></iframe>";
        }
        $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>";
    }

    private function displayGallery($gallery)
    {
        $html = [];
        foreach ($gallery->images as $image) {
            $html[] = "<a class='gallery__item gallery__item--image img' href='{$this->params->get('pixel_cms_url')}$image->url' style='background-image: url({$this->params->get('pixel_cms_url')}/$image->url)'></a>";
        }
        foreach ($gallery->videos as $video) {
            $html[] = "<div class='gallery__item gallery__item--video' style='background-image: url($video->thumb)'></div>";
        }
        return implode('', $html);
    }

    public function hasSidebar($sidebar = ['workers','pdfs','files'])
    {
        foreach ($sidebar as $attachment) {
            if ($this->hasAttachment($attachment)) return true;
        }
        return false;
    }

    public function hasAttachment($attachment_name)
    {
        return isset($this->article->attachments->{$attachment_name}) && $this->article->attachments->{$attachment_name};
    }

    public function attachPlayerScripts()
    {
        $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);
                                    }
                                }
                            }
                        });
                    });
                }
            ';
        }
        $script = array_map(function($value) {
            return preg_replace('/[\s]{2,}/', '', $value);
        }, $script);
        $html[] = '<script>' . implode("", $script) . '</script>';
        return implode("\n", $html);
    }

    public function displayAttachment($article, $attachment_name)
    {
        $html[] = "<div class='article_attachment article_attachment--$attachment_name'>";
        // $html[] = "<pre>". print_r($article->attachments->{$attachment_name}, true) ."</pre>";

        // Checks if the attachment is set on the article.
        if (!isset($article->attachments->{$attachment_name})) return "";

        $attachment_name_singular = static::$attachments[$attachment_name];
        $attachment_count = count($article->attachments->{$attachment_name} ?? []);

        foreach ($article->attachments->{$attachment_name} as $attachment) {
            $html[] = "<div class='{$attachment_name_singular}'>";
            if ($attachment_name === 'pdfs') {
                $html[] = $this->displayPdf($attachment);
            } else if ($attachment_name === 'galleries') {
                if ($attachment_count > 1) {
                    $html[] = "<h3 class='{$attachment_name_singular}__headline'>$attachment->title</h3>";
                }
                $html[] = "<div class='{$attachment_name_singular}__body'>";
                $html[] = $this->displayGallery($attachment);
                $html[] = "</div>";
            } else if ($attachment_name === 'videos') {
                $html[] = $this->displayVideo($attachment);
            } else if ($attachment_name === 'files') {
                $html[] = $this->displayFile($attachment);
            } else if ($attachment_name === 'workers') {
                $html[] = $this->displayWorker($attachment);
            } else if ($attachment_name === 'departments') {
                if ($attachment_count > 1) {
                    $html[] = "<h3 class='{$attachment_name_singular}__headline'>$attachment->title</h3>";
                }
                $html[] = "<div class='{$attachment_name_singular}__body'>";
                $html[] = $this->displayDepartment($attachment);
                $html[] = "</div>";
            }
            $html[] = "</div>";
        }
        $html[] = "</div>";
        return implode('', $html);
    }

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

        return implode(' ', $classList);
    }

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

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

        return implode(' ', $classList);
    }

	function display($tpl = null, $params = [])
	{
		// Assign data to the view
        $newsData = $this->get('News');
        $this->news = isset($newsData->data) ? $newsData->data : $newsData;
        if (isset($newsData->data)) {
            $this->pagination = (object) [
                'current_page' => (int) $newsData->current_page,
                'per_page' => (int) $newsData->per_page,
                'total' => (int) $newsData->total,
                'last_page' => ceil($newsData->total / $newsData->per_page),
            ];
        }

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

        if (gettype($this->news) === 'array') {
            $tpl = 'listing';
        } else {
            $this->news->bodytext = nl2br(preg_replace('/[\r\n]{2,}/', '</p><p>',  $this->news->bodytext));
        }

        $document = JFactory::getDocument();
        $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);
	}

    public function paginationLink($page, $disabled, $title = null, $active = false)
    {
        $title = $title ?? $page;

        $link = JRoute::_("index.php?Itemid=$this->item_id&page=$page");

        $html[] = '<li class="page-item'. ($disabled ? " disabled" : "") . ($active ? " active" : "") . '">';
        $html[] = '<a class="page-link" href="'.$link.'">' .$title. '</a>';
        $html[] = '</li>';

        return implode('', $html);
    }
}
