<?php

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

class ImportFileProvider
{
    public const EXPORT_URL = 'https://10petitszebres.com/10ptz_export.php?exportkey=Pat5hGfA4tMTNqjuDM28DgRj';
    public const EXPORT_OUTPUT = '10ptz.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> $codePrivileges
     */
    public function download(array $codePrivileges): void
    {
        $source = \fopen(
            self::EXPORT_URL
            . '&' . \http_build_query(['code_privilege' => \implode(',', $codePrivileges)]), '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");
        }
    }
}
