<?php

namespace App\Jobs;

use App\Models\Access;
use App\Models\Gallery;
use App\Models\Image;
use App\Models\Tenant;
use Gumlet\ImageResize;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $image_id;
    public function __construct($id)
    {
        $this->image_id = $id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $image = Image::query()->where("id", "=", $this->image_id)->firstOrFail();
        $gallery = Gallery::query()->where("id", "=", $image->gallery)->firstOrFail();
        $tenant = Tenant::query()->where("id", "=", $gallery->tenant)->firstOrFail();
        $cacheName = "cache/".$tenant->url."_".$gallery->url."_".$image->id;
        $tmpfname = tempnam("/tmp", "FOO").$image->filename;

        //Check if orginal size is cached on the current system
        if (Storage::disk('cache')->exists($cacheName."_orginal")) {
            $file = Storage::disk("cache")->get($cacheName."_orginal");
            file_put_contents($tmpfname, $file);
        } else {
            $this->addAccessLog($tenant->id, $gallery->id, $image->id, "Access", $image->size);
            $file = Storage::disk($image->driver)->get($image->path);
            if(env("CACHE_ORGINAL"))
            {
                Storage::disk("cache")->put($cacheName."_orginal", $file);
            }
            file_put_contents($tmpfname, $file);
        }
        $image->exifRead = true;
        try{
            $exit = exif_read_data($tmpfname);
            if(array_key_exists("DateTimeOriginal", $exit))
            {
                $image->DateTimeOriginal = $exit["DateTimeOriginal"];
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }


        if(empty($image->name)) {
            $image->name = $image->filename;
        }
        $image->saveOrFail();
        unlink($tmpfname);
    }

    private function addAccessLog(int $tenant, int $gallery, int $image, string $typ, int $size) {
        $access = new Access();
        $access->year = date("Y");
        $access->month = date("m");
        $access->day = date("d");
        $access->hour = date("H");
        $access->image = $image;
        $access->gallery = $gallery;
        $access->tenant = $tenant;
        $access->typ = $typ;
        $access->size = $size;
        $access->saveOrFail();
    }
}
