<?php
/**
 * FileController
 * 
 * @author Visual Media
 */

namespace VisualM\MediaManagerBundle\Controller;

use Exception;
use GeSHi\GeSHi;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Translation\Translator;
use VisualM\BlockManagerBundle\Annotation\Block;
use VisualM\BlockManagerBundle\Annotation\BlockLayout;
use VisualM\MediaManagerBundle\Configuration\ConfigurationInterface;
use VisualM\MediaManagerBundle\FileSystem\File;
use VisualM\MediaManagerBundle\FileSystem\Folder;

/**
 * FileController
 * 
 * @BlockLayout(layout="filemanager")
 * 
 * @author Visual Media
 */
class FileController extends ControllerBase
{

    /**
     * Create Breadcrumbs from relative path
     * This function does not check if the relative path is correct
     * 
     * @param string $relative_path Relative path
     * 
     * @return array Breadcrumb items
     */
    private function getBreadCrumbs($relative_path)
    {
        $breadcrumbs = array(array(
            'path' => $relative_path,
            'name' => basename($relative_path)
        ));
        while($relative_path !== DIRECTORY_SEPARATOR) {
            $relative_path = join(DIRECTORY_SEPARATOR, array_slice(explode(DIRECTORY_SEPARATOR, $relative_path), 0, -2)) . DIRECTORY_SEPARATOR;
            $breadcrumbs[] = array(
                'path' => $relative_path,
                'name' => basename($relative_path)
            );
        }       
        $breadcrumbs =  array_reverse($breadcrumbs);
        return $breadcrumbs;
    }
    
    /**
     * Download File
     * 
     * @param Request $request HTTP Request
     * @param string  $config  Configuration to load
     * 
     * @return Response Download response
     */
    public function downloadAction(Request $request, $config)
    {
        $configuration = $this->getConfiguration($config);
        $rel_path = $request->query->get('path', DIRECTORY_SEPARATOR);
        $path = $this->getFullpath($configuration->getBasePath(), $rel_path);   
        
        // Check if an file.. we cannot download a folder.. or can we..
        if (!is_file($path)) {
            throw new Exception(sprintf('Given path "%s" should be a file, folder given', $rel_path));
        }
        
        $response = new BinaryFileResponse($path);
        $response->trustXSendfileTypeHeader();
        $response->setContentDisposition(
            ResponseHeaderBag::DISPOSITION_INLINE,
            basename($path),
            basename($path)
        );
        
        return $response;
    }
  
    /**
     * View File
     * 
     * @Block(view="VisualMMediaManagerBundle:File:sidebar.html.twig", position="sidebar")
     * @Block(view="VisualMMediaManagerBundle:File:header.html.twig", position="top")
     * @Block(view="VisualMMediaManagerBundle:File:view.html.twig", position="main")
     * 
     * @param Request $request HTTP Request
     * @param string  $config  Configuration to load
     * 
     * @return array Data for View
     */
    public function viewAction(Request $request, $config)
    {       
        $configuration = $this->getConfiguration($config);
        $rel_path = $request->query->get('path', DIRECTORY_SEPARATOR);
        $path = $this->getFullpath($configuration->getBasePath(), $rel_path);   
        
        // Check if an file.. we cannot view a folder.. or can we..
        if (!is_file($path)) {
            throw new Exception(sprintf('Given path "%s" should be a file, folder given', $rel_path));
        }
        
        // Get File info
        $spl_file = new SplFileInfo($path, $configuration->getBasePath(), $rel_path);
        $file = new File($configuration, '', $spl_file);
        
        // Check if we need to pass contents to view
        $viewer_config = $file->getViewer();
        if ($viewer_config[1]) {
            $contents = $spl_file->getContents();
        } else {
            $contents = null;
        }
        
        // Set GeSHi settings
        if ($viewer_config[0] == 'geshi') {
            $highlighter = $this->get('dt_geshi.highlighter');
            $highlighter->setDefaultOptions(function($geshi){
                /* @var $geshi GeSHi */
                $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 2);
                $geshi->set_line_style('background: #fcfcfc;', 'background: #f9f9f9;');            
            });
        }
        
        // Check if callback is given
        if (null !== ($fs_callback = $request->query->get('fs_callback', null))) {
            $cb_path = $file->getWebPath();
        } else {
            $cb_path = null;
        }
        
        
        return array(
            'page_title'       => basename($rel_path),
            'config'           => $config,
            'path_breadcrumbs' => $this->getBreadCrumbs($rel_path . DIRECTORY_SEPARATOR),
            'rel_path'         => $rel_path,
            'extra_args'       => $this->getExtraArgs($request),
            'cb_path'          => $cb_path,
            'viewer'           => $file->getViewer(),
            'contents'         => $contents,
            'details'          => $file->getDetails()            
        );
    }

}
