<?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;
    }

    public function download(): void
    {
        $source = \fopen(self::EXPORT_URL, '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()) {
            $this->download();
        }

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

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

        return $ret;
    }
}
