<?php

namespace App\Jobs;

use App\Imports\NomenclaturesImport;
use App\Imports\ProjetsImport;
use App\Notifications\Import\ImportNotification;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Mockery\Exception;

class ImportExcel implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private $_requestBy;
    private $_filepath;
    private $_contexte;

    /**
     * Create a new job instance.
     *
     * @param $requestBy
     * @param $filepath
     * @param $context
     */
    public function __construct($requestBy, $filepath, $context)
    {
        $this->_requestBy = $requestBy;
        $this->_filepath = $filepath;
        $this->_contexte = $context;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            // On redirige l'import en fonction de son contexte
            if ($this->_contexte === 'nomenclature') {
                Excel::import(new NomenclaturesImport($this->_requestBy), $this->_filepath, 'local');
            }

            if ($this->_contexte === 'projet') {
                Excel::import(new ProjetsImport($this->_requestBy), $this->_filepath, 'local');
            }

        } catch (Exception $e) {
            // S'il y a une exception elle est gérée par la méthode failed
            $this->failed($e);
        } finally {
            // A la fin du job on peut supprimer le fichier excel du storage
            Storage::delete($this->_filepath);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::error('Erreur lors d\'un import Excel (contexte : ' . $this->_contexte . ') : ' . $exception->getMessage());
        $this->_requestBy->notify(new ImportNotification('Une erreur inconnue est survenue durant l\'import'));
    }
}
