<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\Index\Persistence;

use Magento\Mray\MagentoApiIndex\Model\Versions;
use function clearstatcache;
use function is_dir;
use function mkdir;
use function realpath;

class MagentoReleaseStorage
{
    /**
     * @var string|false
     */
    private $directory;

    /**
     * @var Versions
     */
    private $versions;

    /**
     * @param string $dataDir
     */
    public function __construct(string $dataDir)
    {
        if (!is_dir($dataDir)) {
            mkdir($dataDir, 0755, true);
            clearstatcache(true, $dataDir);
        }

        $this->directory = realpath($dataDir);
        $this->versions = new Versions();
    }

    /**
     * @param string $version
     */
    public function append(string $version): void
    {
        $reader = new FileReader();
        $writer = new FileWriter();

        $file = $this->directory . '/releases.php';

        $releases = $reader->read($file);

        if (!isset($releases[$version])) {
            $releases[$version] = count($releases);
        }

        $writer->write($file, $releases);
    }

    /**
     * @param string $version
     * @param string $mask
     * @return string
     */
    public function mask(string $version, string $mask = ''): string
    {
        return $this->versions->addToMask($version, $mask);
    }

    /**
     * @param string $version
     * @param string $mask
     * @return bool
     */
    public function isInMask(string $version, string $mask): bool
    {
        return $this->versions->isInMask($version, $mask);
    }
}
