<?php
namespace DevOwl\RealThumbnailGenerator\lite\attachment;

use DevOwl\RealThumbnailGenerator\attachment\Regenerate;
use DevOwl\RealThumbnailGenerator\attachment\Thumbnail as AttachmentThumbnail;
use WP_Error;

// @codeCoverageIgnoreStart
defined('ABSPATH') or die('No script kiddies please!'); // Avoid direct file request
// @codeCoverageIgnoreEnd

trait Thumbnail {
    // Documented in IOverrideThumbnail
    public function getSchemaFolder() {
        add_option('rtg_thumbnail_folder', '');
        $value = get_option('rtg_thumbnail_folder');
        return strlen(trim($value)) === 0 ? '' : trim($value, '/');
    }

    // Documented in IOverrideThumbnail
    public function getSchemaFilename() {
        add_option('rtg_thumbnail_filename', '');
        $value = get_option('rtg_thumbnail_filename');
        return strlen(trim($value)) === 0 ? AttachmentThumbnail::DEFAULT_SCHEMA_FILENAME : trim($value, '/');
    }

    // Documented in IOverrideThumbnail
    public function deleteUnused($ids) {
        if (is_numeric($ids)) {
            $ids = [$ids];
        }
        if (!is_array($ids)) {
            return false;
        }
        $result = [];

        $GLOBALS['rtg_suppress_update_metadata'] = true;

        // Iterate all ids
        foreach ($ids as $value) {
            $result[$value] = $this->_deleteUnused($value);
        }

        unset($GLOBALS['rtg_suppress_update_metadata']);
        return $result;
    }

    /**
     * Delete unused image sizes of a single post ID.
     *
     * @param int $postId The post id
     * @return true|WP_Error
     */
    private function _deleteUnused($postId) {
        $check = $this->check($postId);
        if (is_wp_error($check)) {
            return $check;
        }

        // Nothing to delete
        if (count($check['deletable']) === 0) {
            return true;
        }

        $dirname = dirname($check['attachedFile']);
        $meta = $check['meta'];

        // Start delete process
        $cntSuccess = 0;
        foreach ($check['deletable'] as $name => $value) {
            $toDelete = trailingslashit($dirname) . $value['file'];
            $currentSuccess = false;
            if (file_exists($toDelete)) {
                //$filesize = filesize($toDelete);
                if (@unlink($toDelete)) {
                    $currentSuccess = true;
                } else {
                    $error = new WP_Error(
                        'delete-fails',
                        __(
                            'One or more thumbnail sizes could not be deleted. Please check the read and write permissions of the upload folder (usually wp-content/uploads/)!',
                            'real-thumbnail-generator-lite'
                        )
                    );
                    break;
                }
            } else {
                $currentSuccess = true;
            }
            if ($currentSuccess) {
                unset($meta['sizes'][$name]);
                unset($check['deletable'][$name]);
                $check['deletableSpace'] = 0;
                ++$cntSuccess;
            }
        }

        // Update the post meta again so the deleted array value is gone
        if ($cntSuccess > 0) {
            wp_update_attachment_metadata($postId, $meta);
            Regenerate::getInstance()->synchronize($postId, $check);
            return true;
        }

        return isset($error)
            ? $error
            : new WP_Error('delete-fails2', __('Something went wrong.', 'real-thumbnail-generator-lite'));
    }
}
