<?php

namespace Snaju\Inception\Http\Request;

use Snaju\Inception\Util\MimeType;

class RequestFile
{

    private int $error = 0;

    private string $name;

    private string $ext;

    private int $size;

    private string $tmpName;

    private string $mimeType;

    /**
     * RequestFile constructor.
     * @param string $tmpName
     * @param string $mimeType
     */
    public function __construct(array $file)
    {
        $this->error = $file['error'];
        if ($this->error == 0) {
            $this->name = $file['name'];
            $this->size = $file['size'];
            $this->ext = $file['type'];
            $this->tmpName = $file['tmp_name'];
            $this->mimeType = MimeType::getType(file_get_contents($this->tmpName));
        }
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getExt(): string
    {
        return $this->ext;
    }

    /**
     * @return int|string
     */
    public function getSize(): int|string
    {
        return $this->size;
    }

    /**
     * @return string
     */
    public function getTmpName(): string
    {
        return $this->tmpName;
    }

    /**
     * @return false|string
     */
    public function getMimeType(): bool|string
    {
        return $this->mimeType;
    }

    public function getData()
    {
        return file_get_contents($this->tmpName);
    }

    public function move($path)
    {
        file_put_contents($path, $this->getData());
    }

    public function delete()
    {
        unlink($this->tmpName);
    }

    public function hasUploadError()
    {
        return ($this->error != 0);
    }

    /**
     * @return int|mixed
     */
    public function getUploadError(): mixed
    {
        return $this->error;
    }
}
