<?php
namespace IntellexApps\PHP\UploadFile\Domain\Service;
use Eventviva\ImageResize;
use IntellexApps\PHP\UploadFile\Util\Inflector;

/** Main upload file logic resides here */
class ThumbnailService extends BaseService
{

    const THUMBS_DIR = '.thumbs';

    /**
     * Output thumbnail for path
     *
     * @param $path
     */
    public function outputThumbnail($path)
    {
        $fullUrl = $this->get('upload')->getFullPath($path);

        $thumbPath = $this->getThumbPath($path);

        // TODO: Use file system service here
        if(!is_dir(dirname($thumbPath))) {
            mkdir(dirname($thumbPath), 0777, true);
        }

        if(!$this->get('file_system')->fileExists($thumbPath)) {
            $image = new ImageResize($fullUrl);
            $image->resizeToBestFit(200, 150);
            $image->save($thumbPath);
        }

        $contentType = mime_content_type($thumbPath);

        // Output file
        header("Content-Type: " . $contentType);
        header("Content-Disposition: inline; filename='" . basename($thumbPath) . "'");

        readfile($thumbPath);
        exit();
    }

    /**
     * Get thumb path
     *
     * @param $path
     * @return string
     */
    private function getThumbPath($path)
    {
        return Inflector::joinPaths([
            $this->getThumbnailFolder(),
            $path
        ]);
    }

    /**
     * Get thumbnail folder
     *
     * @return mixed
     */
    private function getThumbnailFolder()
    {
        $dirName = self::THUMBS_DIR;

        $fullPath = $this->get('upload')->getFullPath($dirName);

        // TODO: Use file_system service for this
        if(!is_dir($fullPath)) {
            mkdir($fullPath, 0777, true);
        }

        return $fullPath;
    }
}
