<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Model\Indexer\Locator;

use Magento\Indexer\Model\ResourceModel\Mview\View\State\CollectionFactory;

class SnapshotMViewStateTable implements SnapshotMViewStateTableInterface
{
    /**
     * @var
     */
    private $snapShoot;
    /**
     * @var CollectionFactory
     */
    private $collection;

    public function __construct(CollectionFactory $collection)
    {
        $this->collection = $collection;
    }

    /**
     * Snap shoot mview_state table
     * @return void
     */
    public function snapShoot()
    {
        if ($this->snapShoot) {
            return;
        }
        $stateCollection = $this->collection->create();

        foreach ($stateCollection->getData() as $view) {
            $this->snapShoot[$view['view_id']] = $view['version_id'];
        }
    }

    /**
     * Get VersionId
     * @param $viewId
     * @return int|mixed
     */
    public function getVersionId($viewId)
    {
        if (!isset($this->snapShoot[$viewId])) {
            return 0;
        }
        return $this->snapShoot[$viewId];
    }

    /**
     * Get Version Id Or throw exception
     * ATTENTION: not implemented yet, test it first
     * @param $viewId
     * @return void
     * @throws \Exception
     */
    public function getVersionIdOrThrow($viewId)
    {
        if (!isset($this->snapShoot[$viewId])) {
            throw new \Exception('');
        }
        return $this->snapShoot[$viewId];
    }
}
