<?php

namespace App\Classes\Jobs\Commands\V2;


use Carbon\Carbon;
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\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class HouseKeepingS3FilesV2CommandJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Housekeeping temporary files in S3 Bucket.');
        $start   = new Carbon();

        $s3 = Storage::disk('s3');
        $directories = [
            'temp',
        ];
        foreach ($directories as $directory) {
            $startInner = Carbon::now();
            Log::info(Carbon::now() . ' [HouseKeepingS3FilesV2] Start cleaning - ' . $directory);

            $objects = $s3->allFiles($directory);

            foreach ($objects as $object) {
                $s3->delete($object);
                Log::info('[HouseKeepingS3FilesV2] Deleted object: ' . $object);
            }

            Log::info('[HouseKeepingS3FilesV2] All files have been deleted.');

            $endInner = Carbon::now();
            $elapsedTime = $startInner->diff($endInner)->format('%H:%I:%S');
            Log::info(Carbon::now() . ' [HouseKeepingS3FilesV2] Process ended. ElapsedTime: ' . $elapsedTime);
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Housekeeping temporary files in S3 Bucket. ElapsedTime: ' . $elapsedTime . '.');
    }
}
