<?php

namespace App\Repositories\Core;

use Illuminate\Support\Facades\Storage;
use SoftCreatR\MimeDetector\MimeDetector;
use SoftCreatR\MimeDetector\MimeDetectorException;

class File
{
    public static function copy($source, $target)
    {
        $source = self::sanitize($source);
        $target = self::sanitize($target);
        if (! self::checkFile($source)) {
            return false;
        }
        $dirname = self::relative(dirname($target));
        self::checkDirOrCreate($dirname);

        return copy($source, $target);
    }

    public static function checkDirOrCreate($dir)
    {
        return self::checkDir($dir) ? true : self::createDir($dir);
    }

    public static function sanitize($filename)
    {
        return str_replace('\\', '/', $filename);
    }

    public static function relative($filename)
    {
        return str_replace(self::getStorageAppPath(), '', $filename);
    }

    public static function getStorageAppPath()
    {
        return self::sanitize(storage_path()).'/app';
    }

    public static function getTree($path)
    {
        $tree = [];

        $branch = [
            'label' => basename($path),
        ];

        foreach (\File::files($path) as $file) {
            $branch['children'][] = basename($file);
        }

        foreach (\File::directories($path) as $directory) {
            $branch['children'][] = self::getTree($directory);
        }

        return array_merge($tree, $branch);
    }

    public static function list($dir, $mask = '/*')
    {
        return glob($dir);
    }

    public static function checkDir($dir)
    {
        // return File::isDirectory($dir)
        return is_dir($dir);
    }

    public static function checkFile($file)
    {
        return file_exists($file);
    }

    public static function createDir($dir)
    {
        return Storage::makeDirectory($dir);
    }

    public static function deleteDir($dir)
    {
        return Storage::deleteDirectory($dir);
    }

    public static function createFile($file, $content)
    {
        return Storage::put($file, $content);
    }

    public static function getFile($file)
    {
        return Storage::get($file);
    }

    public static function getFilesize($file)
    {
        return Storage::size($file);
    }

    public static function getUrlFile($file)
    {
        return Storage::url($file);
    }

    public static function download($file, $name = false, $headers = false)
    {
        return Storage::download($file, $name, $headers);
    }

    public static function getFileType($file)
    {
        try {
            return (new MimeDetector())->setFile($file)->getFileType();
        } catch (MimeDetectorException $e) {
            exit('An error occured while trying to load the given file.');
        }
    }

    public static function replaceInFile($path, $string, $replace)
    {
        set_time_limit(0);
        $temp = false;

        if (is_file($path) === true) {
            $file = fopen($path, 'r');
            $temp = tempnam('./', 'tmp');

            if (is_resource($file) === true) {
                while (feof($file) === false) {
                    file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
                }

                fclose($file);
            }

            unlink($path);
        }

        return $temp ? rename($temp, $path) : false;
    }
}
