<?php

namespace App\Services;

use App\Models\Asset;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class FileDownloadService {
    protected array $documentMimes = [
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'doc' => 'application/msword',
        'pdf' => 'application/pdf',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xls' => 'application/vnd.ms-excel',
        'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
    ];
    protected array $imageMimes = [
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpeg',
        'png' => 'image/png'
    ];


    public function __construct() {
    }


    public function download($url, $dir = null, $filename = null): ?Asset {
        $info = pathinfo($url);
        $ext = $info['extension'] ?? null;
        if (!empty($this->documentMimes[$ext])) $path = 'public/documents';
        elseif (!empty($this->imageMimes[$ext])) $path = 'public/images';

        if (!empty($path)) {echo("$url is trying to download\n");
            $filename = $filename ? "{$filename}.{$ext}" : $info['basename'];
            $path = $dir ? "{$path}/{$dir}/{$filename}" : "{$path}/{$filename}";
            $asset = Asset::query()->where(['path' => $path])->first();
            if (!$asset && Storage::put($path, Http::get($url)->body())) {
                $asset = $this->makeAsset($path);
                echo("Downloaded {$asset->path}\n");
            } elseif ($asset) echo("{$asset->path} already exist\n");
        }
        return $asset ?? null;
    }
    public function makeAsset($path, $name = null) {
        $info = pathinfo($path);
        return Asset::create([
            'type' => !empty($this->documentMimes[$info['extension'] ?? null]) ? 'document' : 'image',
            'path' => $path,
            'mime' => $this->mimes[$info['extension']] ?? null,
            'name' => $name ?? $info['basename'],
            'filename' => $info['basename'],
            'extension' => $info['extension'],
            'user_id' => ($user = Auth::user()) ? $user->id : null
        ]);
    }


}