<?php

namespace App\Jobs;

use Illuminate\Http\File;
use Illuminate\Bus\Queueable;
use App\Models\ClientCollection;
use Rap2hpoutre\FastExcel\FastExcel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Illuminate\Queue\InteractsWithQueue;
use App\Http\Resources\GwStationResource;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Http\Controllers\V1\QueryTraits\GwApiQuery;

class GwCsvExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use GwApiQuery;

    protected $data;
    protected $exportFileName;
    protected $clientCollectionId;

    public function __construct($data, $clientCollectionId, $exportFileName = null)
    {
        $this->data = $data;
        $this->exportFileName = $exportFileName;
        $this->clientCollectionId = $clientCollectionId;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $ClientCollection = ClientCollection::find($this->clientCollectionId);

        $tmpFileName = time().rand().'.csv';

        $exportFileName = $this->exportFileName ? $this->exportFileName : 'leo-bwdb-gw-auto-'.now()->format('YmdHis');

        if(!Storage::disk('local')->exists('tmp')) {
            Storage::disk('local')->makeDirectory('tmp');
        }

        $datas = GwStationResource::collection($this->getGwAllDataQuery($this->data, $this->clientCollectionId));

        (new FastExcel(json_decode(collect($datas)->toJson(), true)))->export(storage_path('app/tmp/'.$tmpFileName));

        if($ClientCollection->ftp_host) {
            config([
                'filesystems.disks.ftp' => [
                    'driver' => 'ftp',
                    'host' => $ClientCollection->ftp_host,
                    'username' => $ClientCollection->ftp_user,
                    'password' => $ClientCollection->ftp_pass,
                    'port' => (int) $ClientCollection->ftp_port,
                    'root' => $ClientCollection->ftp_dir,
                ],
            ]);

            $data = Storage::disk('ftp')->putFileAs('/', new File(storage_path('app/tmp/'.$tmpFileName)), '/'.$exportFileName.'.csv');
        }

        if($data) {
            Storage::disk('local')->delete('tmp/'.$tmpFileName);
        }
    }
}
