<?php

namespace Ignite\Core\Files;

use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\Exportable;

class CsvFileGenerator extends FileGenerator
{
    /**
     * @var Exportable
     */
    private $excelExport;

    public function __construct($excelExport)
    {
        $uses = array_flip(class_uses_recursive($excelExport));

        if (! isset($uses[Exportable::class])) {
            // Could not find an interface or class to look for to ensure we have the desired ->store() method.
            throw new \InvalidArgumentException("excelExport needs to use the Exportable trait.");
        } else if ($excelExport instanceof ShouldQueue) {
            throw new \InvalidArgumentException(
                'Unable to handle queued exports right now since we\'ll need the generated file to be returned. '.
                get_class($this->excelExport).' will be queued.'
            );
        }

        $this->excelExport = $excelExport;
    }

    /**
     * {@inheritdoc}
     */
    protected function generateFile(): TemporaryFile
    {
        $saveFile = $this->temporaryFileBuilder()->extension('csv')->make();
        $wasStored = $this->excelExport->store($saveFile->getRelativePath(), $saveFile->getDisk(), 'Csv');

        if (! $wasStored) {
            throw new \RuntimeException('Unable to save excel file with '.get_class($this->excelExport));
        }

        return $saveFile;
    }
}
