<?php
/**
 * @package     FILEman
 * @copyright   Copyright (C) 2011 Timble CVBA. (http://www.timble.net)
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.joomlatools.com
 */

defined( '_JEXEC' ) or die;

jimport('joomla.plugin.plugin');

class plgButtonAttachments extends JPlugin
{
    protected $_extensions = array('docman' => array('document'), 'content' => array('article', 'form'), 'textman' => array('article'));

    public function __construct(&$subject, $config)
    {
        parent::__construct($subject, $config);
        $this->loadLanguage();
    }

    public function onDisplay($name)
    {
        $button = null;

        if (class_exists('Koowa')) {
            $application = JFactory::getApplication();

            if ($data = $this->_getContextData($application))
            {
                $button = new JObject();
                $button->class = 'btn fileman-attachments';

                $editor = JFactory::getConfig()->get('editor');

                $is_joomlatools_extension = false;
                $is_joomla4               = version_compare(JVERSION, '4.0', '>=');

                $link = 'index.php?option=com_fileman&amp;view=attachments&amp;e_name=' . $name . '&amp;layout=editor&amp;container=fileman-attachments&amp;table=' . rawurlencode($data->table) . '&amp;row=' . rawurlencode($data->row);

                try
                {
                    if (class_exists('Koowa') && class_exists('KObjectManager')) {
                        $is_joomlatools_extension = (boolean) KObjectManager::getInstance()->isRegistered('dispatcher');
                    }
                } catch (Exception $e) {}

                if (!$is_joomlatools_extension)
                {
                    // Use Joomla modal
                    $button->set('modal', true);
                    $button->set('options', "{handler: 'iframe', size: {x: 1000, y: 600}}");
                    $button->set('link', $link);
                }
                else
                {
                    if ($is_joomla4)
                    {
                        $button->set('link', '#');
                        $onclick = 'kQuery.magnificPopup.open({type: "iframe", items: {src: "' . str_replace('&amp;', '&', $link) . '"}, mainClass: "k-editor-modal"})';

                        if ($editor != 'tinymce') {
                            $onclick = htmlspecialchars($onclick); // Editors render the property in the button tag, needs escaping
                        }

                        $button->set('onclick', $onclick);
                    }
                    else
                    {
                        $button->set('class', 'btn k-js-iframe-modal fileman-attachments'); // Open using MagnificPopup}
                        $button->set('link', $link);
                    }
                }

                if ($is_joomla4)
                {
                    $button->icon    = 'attachment';
                    $button->iconSVG = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="-1 -1 10 10">
                                            <path d="M5 0c-.51 0-1.02.21-1.41.59l-2.78 2.72c-1.07 1.07-1.07 2.8 0 3.88 1.07 1.07 2.8 1.07 3.88 0l1.25-1.25-.69-.69-1.16 1.13-.09.13c-.69.69-1.81.69-2.5 0-.68-.68-.66-1.78 0-2.47l2.78-2.75c.39-.39 1.04-.39 1.44 0 .39.39.37 1.01 0 1.41l-2.5 2.47c-.1.1-.27.1-.38 0-.1-.1-.1-.27 0-.38l.06-.03.91-.94-.69-.69-.97.97c-.48.48-.48 1.27 0 1.75s1.27.49 1.75 0l2.5-2.44c.78-.78.78-2.04 0-2.81-.39-.39-.89-.59-1.41-.59z"/>
                                        </svg>';
                }

                $button->set('text', JText::_('PLG_ATTACHMENTS_BUTTON_FILE'));
                $button->set('name', 'attachment');

                JHtml::_('stylesheet', 'media/koowa/com_koowa/css/modal-override.css');
            }
        }


        return $button;
    }

    protected function _getContextData($application)
    {
        $data = null;

        $input = $application->input;

        foreach ($this->_extensions as $extension => $views)
        {
            $option = 'com_' . $extension;

            if ($input->get('option') == $option && in_array($input->get('view'), $views))
            {
                $method = sprintf('_getContextData%s', ucfirst($extension));

                if (method_exists($this, $method)) {
                    if ($data = (object) $this->$method($application)) break;
                }
            }
        }

        return $data;
    }

    protected function _getContextDataContent($application)
    {
        $input = $application->input;

        $table = 'content';
        $count = 0;

        if ($application->isClient('administrator')) {
            $row = $input->getInt('id', 0);
        } else {
            $row = $input->getInt('a_id', 0);
        }

        if (!$row) {
            $row = $this->_getRandomInt() * (-1);
        } else {
            $count = $this->_getAttachmentsCount($row, $table);
        }

        return array('table' => $table, 'row' => $row, 'count' => $count);
    }

    protected function _getContextDataDocman($application)
    {
        $input = $application->input;

        $table = 'docman_documents';
        $count = 0;

        if (JFactory::getApplication()->isClient('site'))
        {
            if ($row = $input->get('slug', '', 'raw'))
            {
                $row = KObjectManager::getInstance()
                                     ->getObject('com://admin/docman.model.documents')
                                     ->slug($row)
                                     ->fetch()->id;
            }

        }
        else $row = $input->getInt('id', 0);

        if (!$row) {
            $row = $this->_getRandomInt() * (-1);
        } else {
            $count = $this->_getAttachmentsCount($row, $table);
        }

        return array('table' => $table, 'row' => $row, 'count' => $count);
    }

    protected function _getContextDataTextman($application)
    {
        $input = $application->input;

        $table = 'content';
        $count = 0;

        $row = $input->getInt('id', 0);

        if (!$row) {
            $row = $this->_getRandomInt() * (-1);
        } else {
            $count = $this->_getAttachmentsCount($row, $table);
        }

        return array('table' => $table, 'row' => $row, 'count' => $count);
    }

    protected function _getRandomInt()
    {
        list($usec, $sec) = explode(' ', microtime());
        $seed = (float) $sec + ((float) $usec * 100000);

        srand((int)$seed);

        // Temporarily assign a random negative int as the row ID
        return rand();
    }

    protected function _getAttachmentsCount($row, $table)
    {
        return KObjectManager::getInstance()
                             ->getObject('com://admin/fileman.model.attachments')
                             ->table($table)
                             ->row($row)
                             ->count();
    }
}