<?php

namespace Comitium5\DesignerBundle\Helper;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Class FileUtils
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Helper
 */
class FileUtils
{
    /**
     * @param $filePath
     * @param $content
     *
     * @throws \Exception
     */
    public static function create($filePath, $content)
    {
        (new Filesystem())->dumpFile($filePath, $content);
    }

    /**
     * @param $fileName
     * @param $content
     *
     * @return string
     */
    public static function createTmpFile($fileName, $content)
    {
        $tmpPath = self::tmpPath($fileName);

        self::create(
            $tmpPath,
            $content
        );

        return $tmpPath;
    }

    /**
     * @param $filePath
     *
     * @throws \Exception
     */
    public static function remove($filePath)
    {
        (new Filesystem())->remove($filePath);
    }

    /**
     * @param $file
     *
     * @return bool
     */
    public static function exists($file)
    {
        return (new Filesystem())->exists($file);
    }

    /**
     * @param $filePath
     *
     * @return false|string
     */
    public static function read($filePath)
    {
        return file_get_contents($filePath);
    }

    /**
     * @param $fileName
     *
     * @return string
     */
    public static function tmpPath($fileName)
    {
        return trim(sys_get_temp_dir(). DIRECTORY_SEPARATOR . $fileName);
    }

    /**
     * @param $prefix
     *
     * @return string
     */
    public static function createUniqueTmpPath($prefix)
    {
        return trim(tempnam(sys_get_temp_dir(), $prefix));
    }

    /**
     * @param string $filePath
     *
     * @return string
     */
    public static function getMimeType($filePath)
    {
        return mime_content_type($filePath);
    }

    /**
     * @param UploadedFile $file
     *
     * @return bool
     */
    public static function validateFileTyping(UploadedFile $file)
    {
        $extension = $file->guessClientExtension();

        $guessedExtension = $file->guessExtension();

        if (empty($extension) || empty($guessedExtension)) {
            return false;
        }

        return $extension !== $guessedExtension;
    }
}
