<?php

/*
 * Created on Mon Mar 25 2019
 * HomePage: http://dcforo.com/
 * Email: datdaik000@gmail.com
 * Blog: https://fb.com/dcstylexf/
 * Copyright (c) 2019 D.C Style XenForo -  All Rights Reserved
 */

namespace DC\ThreadThumbnail\XF\Entity;

use XF\Mvc\Entity\Entity;
use XF\Mvc\ParameterBag;

class Thread extends XFCP_Thread
{
    /** Check permission */
    public function canEditThumbnail(&$error = null)
    {
        $visitor = \XF::visitor();

        if ($visitor->hasPermission('DC_ThreadThumbnail', 'editThreadThumbnailMod'))
        {
            return true;
        }

        if ($visitor->hasPermission('DC_ThreadThumbnail', 'editThreadThumbnail') && $visitor->user_id == $this->user_id)
        {
            return true;
        }

        return false;
    }
    
    public function canEditCover(&$error = null)
    {
        $visitor = \XF::visitor();

        if ($visitor->hasPermission('DC_ThreadCover', 'editThreadCoverMod'))
        {
            return true;
        }


        if ($visitor->hasPermission('DC_ThreadCover', 'editThreadCover') && $visitor->user_id == $this->user_id)
        {
            return true;
        }

        return false;
    }

    /** Get current thumbnail */
    public function getThumbnail()
    {
        if (!$this->DC_ThreadThumbnail_tempImageUrl)
        {
            return $this->getThumbnailFull();
        }

        return $this->DC_ThreadThumbnail_tempImageUrl;
    }

    public function getThumbnailFull()
    {
        $options = \XF::options();

        if (!in_array($this->node_id, $options->DC_ThreadThumbnail_forumView)) return $options->DC_ThreadThumbnail_noImage;

        switch (true)
        {
            case $this->DC_ThreadThumbnail_thumbCustom:
                return $this->DC_ThreadThumbnail_thumbUrl;
            break;

            default:
                switch(true)
                {
                    case $this->getfirstPostAttach():
                        return $this->getfirstPostAttach();
                    break;

                    case $this->getfirstPostMedia():
                        return $this->getfirstPostMedia();
                    break;

                    case $this->getfirstPostExternal():
                        return $this->getfirstPostExternal();
                    break;

                    default:
                        return $options->DC_ThreadThumbnail_noImage;
                    break;
                }
            break;
        }
    }
    
    public function getThumbnailSmall()
    {
        $options = \XF::options();

        if (!in_array($this->node_id, $options->DC_ThreadThumbnail_forumView)) return $options->DC_ThreadThumbnail_noImage;

        switch (true)
        {
            case $this->DC_ThreadThumbnail_thumbCustom:
                return $this->DC_ThreadThumbnail_thumbUrl;
            break;

            default:
                switch(true)
                {
                    case $this->getfirstPostAttach():
                        return $this->getfirstPostAttachThumbnail();
                    break;

                    case $this->getfirstPostMedia():
                        return $this->getfirstPostMedia();
                    break;

                    case $this->getfirstPostExternal():
                        return $this->getfirstPostExternal();
                    break;

                    default:
                        return $options->DC_ThreadThumbnail_noImage;
                    break;
                }
            break;
        }
    }

    /** Attachment */
    public function getfirstPostAttach()
    {
        $options = \XF::options();
        $baseUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";     

        if (!$this->FirstPost) return;
        
        $attachments = $this->FirstPost->Attachments;

        if ($attachments)
        {
            foreach ($attachments as &$attachment)
            {
                if ( $attachment->has_thumbnail)
                {
                    $attachmentUrl = $baseUrl . \XF::app()->router()->buildLink('attachments', $attachment);
                    return $attachmentUrl;
                    break;
                }
            }
        }

        return;
    }

    /** Attachment */
    public function getfirstPostAttachThumbnail()
    {
        $options = \XF::options();   

        if (!$this->FirstPost) return;
        
        $attachments = $this->FirstPost->Attachments;

        if ($attachments)
        {
            foreach ($attachments as &$attachment)
            {
                if ( $attachment->has_thumbnail)
                {
                    return $attachment->thumbnail_url;
                    break;
                }
            }
        }

        return;
    }
    
    /** External Images */
    public function getfirstPostExternal()
    {
        $options = \XF::options();

        if (!$options->DC_ThreadThumbnail_externalImage) return;

        if (!$this->FirstPost) return;
        
        $message = $this->FirstPost->message;

        $baseUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]"; 

        preg_match('/\[img.*?](.*?)\[\/img]/i',$message,$matches);

        if(!$matches) return;

        $url = $matches[1];

        $linkInfo = \XF::app()->stringFormatter()->getLinkClassTarget($url);
        
        if ($linkInfo['local'])
        {
            return $url;
        }
        
        if(\XF::app()->options()->imageLinkProxy['images'])
        {
            $proxyUrl = \XF::app()->stringFormatter()->getProxiedUrlIfActive('image', $url);
            return $baseUrl . $proxyUrl;
        }

        return $url;
    }

    /** Get first post media thumbnail */
    public function getfirstPostMedia()
    {
        $ytb    = \XF::options()->DC_ThreadThumbnail_youtube;
        $vimeo  = \XF::options()->DC_ThreadThumbnail_vimeo;
        $daily  = \XF::options()->DC_ThreadThumbnail_dailymotion;

        if (!$ytb && !$vimeo && !$daily) return;

        $matchesYtb     = '';
        $matchesVimeo   = '';
        $matchesDaily   = '';

        if (!$this->FirstPost) return;
        
        $message = $this->FirstPost->message;

        if ($ytb)   preg_match('#\[media=youtube\](.+?)\[/media\]#i', $message, $matchesYtb);
        if ($vimeo) preg_match('#\[media=vimeo\](.+?)\[/media\]#i', $message, $matchesVimeo);
        if ($daily) preg_match('#\[media=dailymotion\](.+?)\[/media\]#i', $message, $matchesDaily);

        if (!$matchesYtb && !$matchesVimeo && !$matchesDaily) return;

        switch (true)
        {
            case ($matchesYtb && @(file_get_contents('https://img.youtube.com/vi/'.$matchesYtb[1].'/mqdefault.jpg'))):
                $url = 'https://img.youtube.com/vi/'.$matchesYtb[1].'/maxresdefault.jpg';

                if (!file_exists($url))
                {
                    $url = 'https://img.youtube.com/vi/'.$matchesYtb[1].'/mqdefault.jpg';
                }

                return $url;
            break;

            case ($matchesVimeo && @(file_get_contents('https://vimeo.com/api/v2/video/'.$matchesVimeo[1].'.json'))):
                $url = file_get_contents('https://vimeo.com/api/v2/video/'.$matchesVimeo[1].'.json');

                $url = json_decode($url);

                return $url[0]->thumbnail_medium;
            break;

            case ($matchesDaily && @(file_get_contents('https://www.dailymotion.com/thumbnail/video/'.$matchesDaily[1]))):
                $url = 'https://www.dailymotion.com/thumbnail/video/'.$matchesDaily[1];

                return $url;
            break;

            default:
                return;
            break;
        }
    }


    /************************
     * **********************
     *  Get media video ID 
     * **********************
     * **********************/

    /** Get Youtube video ID */
    public function getYtbVideoID()
    {
        if (!$this->FirstPost) return;
        
        $message = $this->FirstPost->message;

        preg_match('#\[media=youtube\](.+?)\[/media\]#i', $message, $matches);

        if(!$matches) return;

        $id = $matches[1];

        return $id;
    }

    /** Get Vimeo video ID */
    public function getVimeoVideoID()
    {
        if (!$this->FirstPost) return;
        
        $message = $this->FirstPost->message;

        preg_match('#\[media=vimeo\](.+?)\[/media\]#i', $message, $matches);

        if(!$matches) return;

        $id = $matches[1];

        return $id;
    }

    /** Get Dailymotion video ID */
    public function getDailymotionVideoID()
    {
        if (!$this->FirstPost) return;
        
        $message = $this->FirstPost->message;

        preg_match('#\[media=dailymotion\](.+?)\[/media\]#i', $message, $matches);

        if(!$matches) return;

        $id = $matches[1];

        return $id;
    }
}