<?php

namespace DropshippingXmlFreeVendor\WPDesk\Library\DropshippingXmlCore\Service\Limiter;

use DropshippingXmlFreeVendor\WPDesk\Library\DropshippingXmlCore\Infrastructure\Config\Config;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
/**
 * Class FileSizeLimiterService.
 */
class FileSizeLimiterService
{
    public const FILTER_FILES_LIMIT = 'wpdesk_dropshipping_files_limit_mb';
    public const OPTION_LIMIT_UAGE = 'wpdesk_dropshipping_images_download_size';
    private Config $config;
    public function __construct(Config $config)
    {
        $this->config = $config;
    }
    public function is_file_limit_reached(): bool
    {
        if (!$this->is_option_active()) {
            return \false;
        }
        $files_usage = 0;
        $max_file_size_mb = (int) \apply_filters(self::FILTER_FILES_LIMIT, 0);
        if ($max_file_size_mb > 0) {
            $images_usage_reached = $this->get_images_size_in_mb();
            $files_usage = $this->get_files_size();
            $files_usage = $images_usage_reached + $files_usage;
        }
        return $files_usage > $max_file_size_mb;
    }
    public function add_content_size_to_limit(string $content): void
    {
        if (!$this->is_option_active()) {
            return;
        }
        $contents_size = is_string($content) ? strlen($content) : 0;
        unset($content);
        if ($contents_size === 0) {
            return;
        }
        $current_mb = ceil($contents_size / (1024 * 1024));
        $size = $this->get_images_size_in_mb() + $current_mb;
        $this->set_images_size_in_mb($size);
    }
    private function get_files_size(): float
    {
        $dir = $this->config->get_param('files.dir')->getAsString();
        if (!\is_dir($dir)) {
            return (float) 0;
        }
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->config->get_param('files.dir')->getAsString()));
        $total_size = 0;
        foreach ($iterator as $file) {
            $total_size += $file->getSize();
        }
        if ($total_size > 0) {
            $total_size = $total_size / (1024 * 1024);
        }
        return (float) $total_size;
    }
    private function is_option_active(): bool
    {
        return (int) \apply_filters(self::FILTER_FILES_LIMIT, 0) > 0;
    }
    private function get_images_size_in_mb(): int
    {
        return (int) get_option(self::OPTION_LIMIT_UAGE, 0) ?? 0;
    }
    private function set_images_size_in_mb(int $size): void
    {
        \update_option(self::OPTION_LIMIT_UAGE, $size);
    }
}
