<?php
declare(strict_types=1);

namespace Autogedal\EanTools\ViewModel;

use Autogedal\EanTools\Model\ResourceModel\Ean as EanResource;
use Autogedal\EanTools\Model\Spreadsheet\Format;
use Magento\Backend\Model\UrlInterface;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\View\Element\Block\ArgumentInterface;

class Forms implements ArgumentInterface
{
    private ?array $typeProductCounts = null;

    public function __construct(
        private readonly UrlInterface $urlBuilder,
        private readonly FormKey $formKey,
        private readonly EanResource $eanResource,
        private readonly Format $format
    ) {
    }

    public function getUrl(string $path, array $params = []): string
    {
        return $this->urlBuilder->getUrl($path, $params);
    }

    public function getFormKey(): string
    {
        return $this->formKey->getFormKey();
    }

    public function getFormatOptions(): array
    {
        return $this->format->getOptions();
    }

    public function getDefaultFormat(): string
    {
        return Format::DEFAULT_FORMAT;
    }

    public function getAcceptedUploadExtensions(): string
    {
        return '.csv,.txt,.xlsx';
    }

    public function getTypeOptions(): array
    {
        return [
            'simple' => (string)__('Simple'),
            'bundle' => (string)__('Bundle'),
            'configurable' => (string)__('Configurable'),
            'virtual' => (string)__('Virtual'),
            'grouped' => (string)__('Grouped'),
            'downloadable' => (string)__('Downloadable'),
        ];
    }

    public function getTypeProductCounts(): array
    {
        if ($this->typeProductCounts === null) {
            $this->typeProductCounts = $this->eanResource->countProductsByType();
        }

        return $this->typeProductCounts;
    }

    public function isTypeAvailable(string $type): bool
    {
        return ($this->getTypeProductCounts()[$type] ?? 0) > 0;
    }
}
