<?php  // vim:set et ts=4 sw=4 sts=4:
# Copyright (C) 2003-2014 hipplay Inc.
#
# This is UNPUBLISHED PROPRIETARY SOURCE CODE OF hipplay Inc.
# The copyright notice above does not evidence any actual or intended
# publication of such source code. The contents of this file may not
# be disclosed to third parties, copied or duplicated in any form, in
# whole or in part, without the prior written permission of
# hipplay Inc.
#
namespace HipPlayConnect\REST\services\files;



use HipPlayConnect\FileSystem\AxPathMapper;
use HipPlayConnect\REST\AxAbstractRESTService;
use HipPlayConnect\REST\AxRESTResourceNotFoundException;
use HipPlayConnect\REST\AxRESTServiceInterface;

class AxFilesRESTService extends AxAbstractRESTService implements AxRESTServiceInterface {

    const DEBUG_RESOURCE = FALSE;

    protected        $serviceName    = 'files';


    public function getResource (array $URIArray) {
        // Convert the fileid from the URI to a filesystem path
        $fsPath = $this->getPathForFileId($URIArray[0]);

        if (self::DEBUG_RESOURCE) {
            error_log("URIArray: " . json_encode($URIArray, JSON_PRETTY_PRINT));
            error_log($fsPath);
        }

        // We require that the file exists on the filesystem
        if (NULL === $fsPath)
            return NULL;

        // We do not allow direct access to directories
        if (is_dir($fsPath))
            return NULL;

        if (count($URIArray) != 2)
            return NULL;

        $subresource = $URIArray[1];

        try {
            $resource = new AxFileRESTResource($fsPath, $subresource);
        } catch (AxRESTResourceNotFoundException $e) {
            error_log($e);
            return NULL;
        }

        return $resource;
    }

    /**
     * Determine the filesystem path from a file id URI portion
     *
     * @param string $fileid The base64-encoded file identifier
     *
     * @return string The filesystem path of the specified file.
     */
    protected function getPathForFileId ($fileid) {
        $filePath = self::urlDecodeFilePath($fileid);
        return AxPathMapper::mapFilePath($filePath);
    }

    protected function urlEncodeFilePath( $string ) {
        return strtr( rtrim( base64_encode( $string ), '=' ), '+/', '-_' );
    }

    protected function urlDecodeFilePath( $string ) {
        return base64_decode( strtr( $string, '-_', '+/' ) . str_repeat( '=', 4 - strlen( $string ) % 4 ) );
    }

}
