<?php

/**
 * @package         Smile Pack
 * @version         2.1.5-RC4 Free
 * 
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2019 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

defined('_JEXEC') or die('Restricted access');

use NRFramework\Helpers\Widgets\GalleryManager2 as GalleryManagerHelper;
use SmilePack\Helpers\GalleryFiles;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Utility\Utility;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Factory;

class ModSPGalleryInstance
{
	public function onContentPrepareForm(Form &$form, $data)
    {
        if ($data->module !== 'mod_spgallery')
        {
            return $form;
        }
        
		// Display the server's maximum upload size in the field's description
		$max_upload_size_str = HTMLHelper::_('number.bytes', Utility::getMaxUploadSize());
        
        
		$field_desc = $form->getFieldAttribute('@max_file_size', 'description', null, 'params');
		$form->setFieldAttribute('@max_file_size', 'description', Text::sprintf($field_desc, $max_upload_size_str), 'params');
        

		// If the Fileinfo PHP extension is not installed, display a warning.
		if (!extension_loaded('fileinfo') || !function_exists('mime_content_type'))
		{
			Factory::getApplication()->enqueueMessage(Text::_('SPGALLERY_MIME_CONTENT_TYPE_MISSING'), 'warning');
		}
    }

    /**
     * Runs when the module is saved.
     * 
     * @param   object  $context
     * @param   object  $table
     * @param   bool    $isNew
     * 
     * @return  bool
     */
	public function onExtensionBeforeSave($context, $table, $isNew)
	{
        $params = $table->params;

        if (!$params = json_decode($params, true))
        {
            return true;
        }

        

        
        $pass = true;

        $limit_files = isset($params['limit_files']) ? (int) $params['limit_files'] : 8;
        if ($limit_files < 1 || $limit_files > 8)
        {
            Factory::getApplication()->enqueueMessage(Text::_('SPGALLERY_LIMIT_FILES_INVALID'), 'error');
            $pass = false;
        }

        return $pass;
        
    }

    /**
     * Runs when the module is saved.
     * 
     * @param   object  $context
     * @param   object  $table
     * @param   bool    $isNew
     * 
     * @return  void
     */
    public function onExtensionAfterSave($context, $table, $isNew, $oldParams)
	{
        $params = $table->params;

        if (!$params = json_decode($params, true))
        {
            return;
        }

        if (!isset($params['value']['items']))
        {
            return;
        }
        
        if (!is_array($params['value']['items']))
        {
            return;
        }
        
        if (!count($params['value']['items']))
        {
            return;
        }

        // Increase memory size and execution time to prevent PHP errors on datasets > 20K
        set_time_limit(300); // 5 Minutes
        ini_set('memory_limit', '-1');
		
        $fieldParams = (object) [
            'fieldparams' => $params
        ];

        
        $limit_files = 8;

        
        
        // Limit items to limit files value
        if ($limit_files > 0)
        {
            $params['value']['items'] = array_slice($params['value']['items'], 0, $limit_files);
        }
        

        $items = GalleryManagerHelper::moveTempItemsToDestination($params['value']['items'], $fieldParams, $this->getDestinationFolder($table, $params));

        // Regenerate images
        $regenerated_items = GalleryManagerHelper::maybeRegenerateImages('module', $items, null, $table->id, $oldParams);
        if ($regenerated_items)
        {
            $items = $regenerated_items;
        }

		// Save item tags
		$items = GalleryManagerHelper::saveItemTags($items);
        $params['value']['items'] = $items;

        // Only the params changed, so update them directly. Storing the table again
        // would repeat the whole save round trip and re-fire its events.
        $table->params = GalleryFiles::updateModuleParams($table->id, $params);
    }

    /**
     * Runs after the module has been copied by Joomla's "Duplicate" and "Batch > Copy"
     * actions, neither of which fires the extension save events.
     *
     * @param   object  $table
     *
     * @return  void
     */
    public function onModuleDuplicated($table)
    {
        if (!$params = json_decode($table->params, true))
        {
            return;
        }

        // Increase memory size and execution time to prevent PHP errors on datasets > 20K
        set_time_limit(300); // 5 Minutes
        ini_set('memory_limit', '-1');

        // Give the copy its own files
        if (!GalleryFiles::duplicateFiles($table->id, $params))
        {
            return;
        }

        // Update the row directly. Storing the table here would re-enter this event.
        $table->params = GalleryFiles::updateModuleParams($table->id, $params);
    }

    /**
     * Runs after the module has been deleted.
     *
     * @param   string  $context
     * @param   object  $table
     *
     * @return  void
     */
    public function onExtensionAfterDelete($context, $table)
    {
        if (!$params = json_decode($table->params, true))
        {
            return;
        }

        // Increase memory size and execution time to prevent PHP errors on datasets > 20K
        set_time_limit(300); // 5 Minutes
        ini_set('memory_limit', '-1');

        // Delete the files the module owns, its upload folder and its temp folder
        GalleryFiles::deleteFiles($table->id, $params);
    }

    
    
	/**
	 * Returns the destination folder.
	 * 
	 * @param   array  $module
	 * @param   array  $params
	 * 
	 * @return  string
	 */
	private function getDestinationFolder($module, $params)
	{
		return GalleryFiles::getDestinationFolder($module->id, $params);
	}
}