<?php

namespace App\Services\WS;

use App\Models\WS\Gallery;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use stdClass;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class GalleryService
{
    /**
     * Create a new class instance.
     */
    public function __construct(private Gallery $gallery)
    {
        //
    }

    public function data()
    {
        $galleries = $this->gallery->get();
        return $galleries->map(function ($item) {
            $ext  = pathinfo($item->image_path, PATHINFO_EXTENSION);
            $file = new stdClass;
            $file->filename = $item->image;
            $file->filepath = 'data:image/' . $ext . ';base64,' . base64_encode(file_get_contents($item->image_path));
            return $file;
        });
    }

    public function store($data)
    {
        $gallery = [];
        $this->cleanGallery();
        foreach ($data->images as $key => $image) {
            $ext = $image->getClientOriginalExtension();
            $fileName = 'gallery-'.$key.'-' . time() . '.' . $ext;
            Storage::disk('public')->putFileAs('website', $image, $fileName);
            $gallery[] = $this->gallery->create([
                'image' => $fileName
            ]);
        }
        return $gallery;
    }

    private function cleanGallery()
    {
        $this->gallery->orderBy('id')->chunkById(10, function (Collection $galleries) {
            foreach ($galleries as $gallery) {
                if($gallery->image_path && file_exists($gallery->image_path)){
                    unlink($gallery->image_path);
                }
                $gallery->delete();
            }
        });
    }
}
