<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\UploadedFile;

/**
 * @property false|mixed|string path
 * @property false|mixed|string mimetype
 * @property false|int|mixed size
 * @property false|mixed|string original_filename
 * @property mixed|string filename
 * @property int id
 * @property string attachType
 */
class Attachment extends BaseAuditable
{
    protected $appends = ['PublicUrl'];

    public function attachable(): MorphTo
    {
        return $this->morphTo();
    }

    public function addStreamedFile($stream = null, $fileName = null)
    {
        $temp = tmpfile();
        fwrite($temp, $stream);
        $acceptedMime = [
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
            'application/pdf' => 'pdf',

        ];
        $this->mimetype = mime_content_type($temp);
        $this->size = filesize(stream_get_meta_data($temp)['uri']);
        fclose($temp);
        if (! array_key_exists($this->mimetype, $acceptedMime)) {
            return false;
        }
        if ($fileName) {
            $this->original_filename = $fileName;
        }
        $fileExt = $acceptedMime[$this->mimetype];
        $this->filename = (string) \Str::orderedUuid().'.'.$fileExt;
        $this->save();
        $dir = sprintf('%010d', intval(floor($this->id / 1000)));
        $this->path = DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR;
        $fileNameWithPath = DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$this->filename;
        \Storage::disk('attachments')->put($fileNameWithPath, $stream);
        $this->save();

        return $this->id;
        /*
                $attachment = new Attachment;
                $attachment->addFile($file);
                $attachment->attachable()->associate($customer);
                $attachment->save();
        */

    }

    private function makeFilenameWithPath($fileExt = 'tmp'): string
    {
        return $this->getSavePath().DIRECTORY_SEPARATOR.$this->makeFileName($fileExt);
    }

    private function makeFileName($fileExt = 'tmp'): string
    {
        return (string) \Str::orderedUuid().'.'.$fileExt;
    }

    private function getSavePath(): string
    {
        return sprintf('%010d', intval(floor($this->id / 1000)));
    }

    public function addFile(UploadedFile $file): ?Attachment
    {
        if (isset($file) && $file && is_file($file)) {
            $this->mimetype = $file->getMimeType();
            $this->size = $file->getSize();
            $this->filename = $this->makeFileName($file->extension());
            $this->original_filename = $file->getClientOriginalName();
            if (! $this->id) {
                $this->save();
            }
            $this->path = $this->getSavePath();
            \Storage::disk('attachments')->putFileAs($this->getSavePath(), $file, $this->filename);
            $this->save();

            return $this;

            return $this;

            $oldName = $file->getClientOriginalName();
            $this->original_filename = $oldName;
            $path = \Storage::disk('dev')->put('/', $file, ['name' => $oldName]);
            $this->path = $path;

            // \Storage::disk('dev')->download($path);

            $this->filename = $file->getClientOriginalName();
        }

        return null;
    }

    public function removeFile()
    {

        try {
            \Storage::disk('attachments')->delete($this->path.DIRECTORY_SEPARATOR.$this->filename); // false-al ter vissza sikeres torles eseten is
            // var_dump('sikeres torles');
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    public function delete()
    {
        if ($this->removeFile()) {
            return parent::delete(); // TODO: Change the autogenerated stub
        }

        return false;
    }

    public function getPublicUrlAttribute(): string
    {
        return $this->getPublicUrl();
    }

    public function getPublicUrl()
    {
        return \Storage::disk('attachments')->url(str_replace('\\', '/', $this->path));
    }
}
