<?php

class Helper {

    public static function enumerateRecursive($path)
    {
        $files = array();
        $flags = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, $flags));
        foreach ($iterator as $fileInfo) {
            $files[$iterator->getSubPathname()] = file_get_contents($fileInfo->getPathName());
        }
        return $files;
    }

    public static function enumerate($path)
    {
        $files = array();
        $flags = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
        $iterator = new IteratorIterator(new FilesystemIterator($path, $flags));
        foreach ($iterator as $fileInfo) {
            if ($fileInfo->isFile())
                $files[$fileInfo->getFilename()] = file_get_contents($fileInfo->getPathName());
        }
        return $files;
    }

    public static function removeDir($dir, $self = true)
    {
        $it = new RecursiveDirectoryIterator($dir);
        $files = new RecursiveIteratorIterator($it,
                     RecursiveIteratorIterator::CHILD_FIRST);
        foreach($files as $file) {
            if ($file->getFilename() === '.' || $file->getFilename() === '..') {
                continue;
            }
            if ($file->isDir()){
                rmdir($file->getRealPath());
            } else {
                unlink($file->getRealPath());
            }
        }
        if ($self) rmdir($dir);
    }

    public static function buildThemeStorage($fso, $relative = '', $saveToDisk = false)
    {
        static $storage = array();

        $tmpPath = realpath(dirname(__FILE__)) . '/tmp/' . ('' === $relative ? '' : $relative . '/');
        if($saveToDisk && !file_exists($tmpPath)) {
            try {
                mkdir($tmpPath, 0777, true);
            } catch (Exception $e) {
                $this->error('Caught exception to create directory: ' . $tmpPath . ' ' . $e->getMessage());
            }
        }
        if(!array_key_exists('items', $fso) || !is_array($fso['items'])) {
            return;
        }
        foreach ($fso['items'] as $name => $file) {
            if(isset($file['content']) && isset($file['type'])) {
                switch ($file['type']) {
                    case 'text':
                        if($saveToDisk)
                            file_put_contents($tmpPath . $name, $file['content']);
                        $storage[$relative . '/' . $name] = $file['content'];
                        break;
                    case 'data':
                        if($saveToDisk)
                            file_put_contents($tmpPath . $name, base64_decode($file['content']));
                        $storage[$relative . '/' . $name] = base64_decode($file['content']);
                        break;
                }
            } elseif(isset($file['items']) && isset($file['type'])) {
                Helper::buildThemeStorage($file, $relative . '/' . $name, $saveToDisk);
            }
        }
        return $storage;
    }

    public static function createDir($path)
    {
        if (!file_exists($path))
            mkdir($path, 0777, true);
        chmod($path, 0777);
    }

    public static function moveDir($source, $destination)
    {
        $files = Helper::enumerateRecursive($source);
        foreach($files as $path => $content) {
            $pos_last_slash = strrpos($path, "/");
            $fullpath = $destination . '/' . $path;
            if (false !== $pos_last_slash) {
                $currentDir = $destination . '/' . substr($path, 0, $pos_last_slash + 1);
                Helper::createDir($currentDir);
            }
            file_put_contents($fullpath, $content);
        }
    }

    public static function isEmptyDir($dir) {
        if (!is_readable($dir)) return NULL;
            $handle = opendir($dir);
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                return FALSE;
            }
        }
        return TRUE;
    }
}