<?php

namespace Lucent\File;

use Exception;
use Illuminate\Log\Logger;
use Intervention\Image\ImageManager;
use Lucent\Channel\ChannelService;
use Lucent\Record\QueryRecord;

class ImageService
{

    private string $notFoundImage = "/not-found.jpg";

    public function __construct(
        public ImageManager   $imageManager,
        public ChannelService $channelService,
        public Logger         $logger
    )
    {
    }

    public function file(?QueryRecord $record, string $template = ""): string
    {
        if (empty($record)) {
            return $this->notFoundImage;
        }

        $originalPath = $record->_file->path;
        $templateUri = $this->findTemplate($originalPath, $template);

        if ($templateUri === false) {
            $templateUri = $this->createTemplate($originalPath, $template);
        }
        return $this->channelService->channel->filesUrl . "/" . $templateUri;
    }

    private function findTemplate(string $originalPath, string $template): string|false
    {
        $templateUri = "templates/" . $template . "/" . $originalPath;
        $templateFilePath = public_path("storage/" . $templateUri);

        if (file_exists($templateFilePath)) {
            return $templateUri;
        }

        return false;
    }

    private function createTemplate(string $originalPath, string $template): string
    {
        $originalFilePath = public_path("storage/" . $originalPath);
        $templateUri = "/templates/" . $template . "/" . $originalPath;
        $templateFilePath = public_path("storage/" . $templateUri);
        if (!file_exists($originalFilePath)) {
            return $this->notFoundImage;
        }

        if (!file_exists(pathinfo($templateFilePath, PATHINFO_DIRNAME))) {
            $this->make_dir(pathinfo($templateFilePath, PATHINFO_DIRNAME));
        }

        try {
            $image = $this->imageManager->make($originalFilePath);
        } catch (Exception $e) {
            $this->logger->error($e->getMessage());
            return $this->notFoundImage;
        }

        $image = $image->filter(new $this->channelService->channel->imageFilters[$template]);
        try {
            $image = $this->imageManager->make((string)$image->encode('webp', 75));
            $image->save($templateFilePath);
        } catch (Exception $e) {
            $this->logger->error($e->getMessage());
            return $this->notFoundImage;
        }

        return $templateUri;
    }

    private function make_dir(string $path): void
    {
        is_dir($path) || mkdir($path, 0777, true);
    }


}
