<?php
namespace App\Helper;
use App\Entity\File;
use App\Models\Gallery;
use App\Models\Tenant;

class Access {
    const TYPE_S3 = "Access";
    const TYPE_CACHE = "Cache";
    private $valideTyps = [self::TYPE_S3, self::TYPE_CACHE];

    public function add(\App\Models\Image $image,File $file, string $typ) {
        if(!in_array($typ, $this->valideTyps)) {
            throw new \Exception("Invalide Typ for Access Log");
        }

        $this->addAccessLog($image->tenant, $image->gallery, $image->id, $typ, $file->getSize());
    }

    public function addById(int $image_id, File $file, string $typ) {
       $image = \App\Models\Image::query()->where("id", "=", $image_id)->firstOrFail();
       $this->add($image, $file, $typ);
    }

    public function addComplete(\App\Models\Image $image, Gallery $gallery, Tenant $tenant, File $file, string $typ) {
        if(!in_array($typ, $this->valideTyps)) {
            throw new \Exception("Invalide Typ for Access Log");
        }

        $this->addAccessLog($tenant->id, $gallery->id, $image->id, $typ, $file->getSize());
    }

    private function addAccessLog(?int $tenant, ?int $gallery, int $image, string $typ, int $size) {
        $access = new \App\Models\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();
    }
}
