<?php

namespace Myvetshop\Module\Clinique\Import\Kalivet\ImportFile;

class ImportFileProvider
{
    public const EXPORT_URL = 'https://kalivet.com/kalivet_export.php?exportkey=Pat5hGfA4tMTNqjuDM28DgRj';
    public const EXPORT_OUTPUT = 'kalivet.export';
    protected string $temporaryFileName;

    public function __construct()
    {
        $this->temporaryFileName = \sys_get_temp_dir() . DIRECTORY_SEPARATOR . self::EXPORT_OUTPUT;
    }

    public function isCached(): bool
    {
        return \is_file($this->temporaryFileName) && \filesize($this->temporaryFileName) > 0;
    }

    /**
     * @param list<string> $idVetoAlcyon
     */
    public function download(array $idVetoAlcyon): void
    {
        $source = \fopen(
            self::EXPORT_URL
            . '&' . http_build_query(['id_veto_alcyon' => \implode(',', $idVetoAlcyon)]), 'r'
        );

        if (!$source) {
            throw new \Exception("Can't open source URL");
        }

        $destination = \fopen($this->temporaryFileName, 'w');

        if (!$destination) {
            throw new \Exception("Can't open destination file");
        }

        if (false === \stream_copy_to_stream($source, $destination)) {
            \fclose($source);
            \fclose($destination);
            \unlink($this->temporaryFileName);

            throw new \Exception("Can't copy export file");
        }
    }

    /**
     * @return resource
     */
    public function open()
    {
        if (!$this->isCached()) {
            throw new \Exception('Download the export first');
        }

        $ret = \fopen($this->temporaryFileName, 'r');

        if (!$ret) {
            throw new \Exception("Can't open cached file");
        }

        return $ret;
    }

    public function purge(): void
    {
        if (!\unlink($this->temporaryFileName)) {
            throw new \Exception("Can't remove temporary file");
        }
    }
}
