<?php

namespace Drupal\simple_interactive_maps;

use Drupal\Core\TempStore\PrivateTempStore;
use Drupal\Core\TempStore\PrivateTempStoreFactory;

/**
 * Provides a trait for storing form data in a temp store.
 */
trait InteractiveMapFormTempStoreTrait {

  /**
   * The private temp store factory.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  protected PrivateTempStoreFactory $privateTempStoreFactory;

  /**
   * Get the temp store for the map.
   *
   * @param \Drupal\simple_interactive_maps\InteractiveMapInterface $interactive_map
   *   The interactive map.
   *
   * @return \Drupal\Core\TempStore\PrivateTempStore
   *   The temp store.
   */
  protected function getMapTempStore(InteractiveMapInterface $interactive_map): PrivateTempStore {
    $tempStoreId = sprintf('simple_interactive_maps_map_%s', $interactive_map->id());
    return $this->privateTempStoreFactory()->get($tempStoreId);
  }

  /**
   * Get the private temp store factory.
   *
   * @return \Drupal\Core\TempStore\PrivateTempStoreFactory
   *   The private temp store factory.
   */
  protected function privateTempStoreFactory(): PrivateTempStoreFactory {
    if (!isset($this->privateTempStoreFactory)) {
      $this->privateTempStoreFactory = \Drupal::service('tempstore.private');
    }
    return $this->privateTempStoreFactory;
  }

}
