<?php

namespace App\AlbumSources;

use App\Album;
use App\Helpers\MiscHelper;
use App\Photo;
use App\Services\PhotoService;
use Guzzle\Http\EntityBody;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Driver for managing files on the local filesystem.
 * @package App\AlbumSources
 */
class LocalFilesystemSource extends AlbumSourceBase implements IAlbumSource
{
    public function deleteAlbumContents()
    {
        if (file_exists($this->getPathToAlbum()) && is_dir($this->getPathToAlbum()))
        {
            $this->recursiveDelete($this->getPathToAlbum());
        }
    }

    public function deleteThumbnail(Photo $photo, $thumbnail = null)
    {
        return @unlink(
            join(DIRECTORY_SEPARATOR, [
                $this->getPathToAlbum(),
                is_null($thumbnail) ? $this->getOriginalsFolder() : $thumbnail,
                $photo->storage_file_name
            ])
        );
    }

    /**
     * Fetches the contents of a thumbnail for a photo.
     * @param Photo $photo Photo to fetch the thumbnail for.
     * @param string $thumbnail Thumbnail to fetch (or null to fetch the original.)
     * @return EntityBody
     */
    public function fetchPhotoContent(Photo $photo, $thumbnail = null)
    {
        $fh = fopen(
            join(DIRECTORY_SEPARATOR, [
                $this->getPathToAlbum(),
                is_null($thumbnail) ? $this->getOriginalsFolder() : $thumbnail,
                $photo->storage_file_name
            ]),
            'r+'
        );

        return EntityBody::factory($fh);
    }

    public function getName()
    {
        return 'global.album_sources.filesystem';
    }

    public function getUrlToPhoto(Photo $photo, $thumbnail = null)
    {
        $photoUrl = route('downloadPhoto', [
            'albumUrlAlias' => $this->album->url_path,
            'photoFilename' => $photo->storage_file_name
        ]);

        if (!is_null($thumbnail))
        {
            $photoUrl .= sprintf('?t=%s', urlencode($thumbnail));
        }

        return $photoUrl;
    }

    public function saveThumbnail(Photo $photo, $tempFilename, $thumbnail = null)
    {
        $fileInfo = new File($tempFilename);
        $fileInfo->move(
            join(DIRECTORY_SEPARATOR, [
                $this->getPathToAlbum(),
                is_null($thumbnail) ? $this->getOriginalsFolder() : $thumbnail
            ]),
            $photo->storage_file_name
        );
    }

    private function getOriginalsFolder()
    {
        return '_originals';
    }

    private function getPathToAlbum()
    {
        return sprintf('%s/%s', $this->configuration->location, $this->album->url_alias);
    }

    private function recursiveDelete($directory)
    {
        $result = scandir($directory);
        foreach ($result as $file)
        {
            if ($file == '.' || $file == '..')
            {
                continue;
            }

            $fullPath = sprintf('%s/%s', $directory, $file);

            if (is_dir($fullPath))
            {
                $this->recursiveDelete($fullPath);
            }
            else
            {
                unlink($fullPath);
            }
        }

        rmdir($directory);
    }
}