<?php

namespace Velis;

use Velis\Filesystem\FilesystemInterface;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 * Based on SpeichNetUpload created by Simon Speich, www.speich.net
 */
class Uploader
{
    /**
     * @var int
     */
    public $numWrittenBytes = 0;


    /**
     * @var FilesystemInterface
     */
    private $filesystem;


    public function __construct()
    {
        $this->filesystem = App::$di->get('filesystem');
    }


    /**
     * Delete uploaded file.
     * @param string $dir
     * @param string $hash file hash
     */
    public function delete($dir, $hash)
    {
        if ($this->filesystem->delete($dir . $hash)) {
            App::getService('response')->setContent(Lang::get('GENERAL_DELETED'));
        } else {
            App::getService('response')->setStatusCode(404, "Not found")->setContent(Lang::get('GENERAL_FILE_NOT_EXIST'));
        }
    }

    /**
     * Save uploaded file to disk.
     * Note: In this demo files are not written to disk. You have to uncomment the corresponding lines.
     * @param string $dir upload directory
     * @throws Exception
     */
    public function save($dir)
    {
        $headers = getallheaders();
        $request = App::getService('request');
        $contentLength = $request->getHeader('Content-Length') ?: $headers['Content-Length'];
        if (!isset($contentLength)) {
            App::getService('response')->setStatusCode(411, "Length Required")->setContent('Header \'Content-Length\' not set.');
            return;
        }

        // Sanitize all uploaded headers before saving to disk
        $file = current($_FILES);
        $hash = md5('flash-upload' . microtime() . $file['name']);

        if (!is_uploaded_file($file['tmp_name'])) {
            throw new Exception('Wrong file path!');
        }

        if ($this->filesystem->upload($dir . $hash, $file['tmp_name'])) {
            $this->numWrittenBytes = $file['size'];
            App::getService('response')->setStatusCode(201, "Created");
            echo $hash;
        } else {
            App::getService('response')->setStatusCode(505, "Not supported")->setContent(Lang::get('GENERAL_SAVING_ERROR'));
        }
    }


    /**
     * @return int
     */
    public function getNumWrittenBytes()
    {
        return $this->numWrittenBytes;
    }
}
