<?php
// Copyright 1999-2017. Plesk International GmbH. All rights reserved.

namespace Plesk\MigrationLibV8\Common;

use Plesk\MigrationLibV8\Utils\FileUtils;

class SessionDirectory
{
    /**
     * @var \Plesk\MigrationLibV8\Common\SessionDirectory[]
     */
    private static array $_instances = [];

    /**
     * @var string
     */
    private string $_path;

    /**
     * @var string
     */
    private string $_id;

    /**
     * SessionDirectory constructor.
     *
     * @param string $id
     * @param string $path
     */
    private function __construct($id, $path)
    {
        $this->_id = $id;
        $this->_path = $path;
    }

    /**
     * Get session directory for the current extension.
     *
     * @param string $sessionId string identifier of the session; as example you could use date when migration was
     * started, e.g. "20170815101733"
     * @param bool $isInExtensionRoot
     * @return SessionDirectory
     */
    public static function getForCurrentExtension($sessionId, $isInExtensionRoot=false)
    {
        if ($isInExtensionRoot) {
            $sessionsDir = \pm_Context::getVarDir() . 'sessions';
        } else {
            $sessionsDir = \pm_Context::getVarDir() . 'plesk-migrator' . DIRECTORY_SEPARATOR . 'sessions';
        }
        $path = $sessionsDir . DIRECTORY_SEPARATOR . $sessionId;
        if (!array_key_exists($path, self::$_instances)) {
            self::$_instances[$path] = new self($sessionId, $path);
        }
        return self::$_instances[$path];
    }

    /**
     * Get path to the session directory.
     *
     * @return string
     */
    public function getPath()
    {
        return $this->_path;
    }

    /**
     * Get string identifier of the session.
     *
     * @return string
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     * Create session directory if it does not exist.
     */
    public function initialize()
    {
        if (!FileUtils::fileExists($this->getPath())) {
            FileUtils::createDirectory($this->getPath());
        }
    }

    /**
     * Whether migration session directory exists.
     *
     * @return bool
     */
    public function isExists()
    {
        return FileUtils::fileExists($this->getPath());
    }

    /**
     * Remove session directory with all files.
     */
    public function remove()
    {
        if (FileUtils::fileExists($this->getPath())) {
            FileUtils::removeDirectory($this->getPath());
        }
    }
}
