<?php

namespace OCA\GroupfolderFilesystemSnapshots\Manager;

use OCA\GroupfolderFilesystemSnapshots\Manager\PathManager;

use OCA\GroupfolderFilesystemSnapshots\Entity\Snapshot;

class SnapshotManager {
    private PathManager $pathManager;


    public function __construct(PathManager $pathManager){
        $this->pathManager = $pathManager;
    }

    private function validSnapshotId(string $snapshotId) {
        return (preg_match("/^[a-zA-Z0-9-_]+$/", $snapshotId) == 1);
    }

    function snapshotExists(string $snapshotId): bool {
        if($this->validSnapshotId($snapshotId)) {
            $path = $this->pathManager->getSnapshotPath($snapshotId);
            return (file_exists($path) && is_dir($path));
        } else {
            return false;
        }
    }

    function get(string $snapshotId) {
        if(self::snapshotExists($snapshotId)) {
            return new Snapshot($snapshotId);
        } else {
            return false;
        }
        
    }

    function getAll() {
        $iterator = new \FilesystemIterator($this->pathManager->getFilesystemSnapshotsPath());
        foreach ($iterator as $fileinfo) {
            if(!$fileinfo->isDir()) continue;
            yield new Snapshot($fileinfo->getFilename());
        }
    }
}