<?php

namespace Drupal\straker_translate\Form;

use Drupal\Core\Entity\EntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\straker_translate\StrakerTranslateProfileUsageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a form for straker_translate profiles deletion.
 */
class StrakerTranslateProfileDeleteForm extends EntityDeleteForm {

  /**
   * The Straker Translate profiles usage service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateProfileUsageInterface
   */
  protected $profileUsage;

  /**
   * Constructs a new StrakerTranslateProfileDeleteForm object.
   *
   * @param \Drupal\straker_translate\StrakerTranslateProfileUsageInterface $profile_usage
   *   The Straker Translate profiles usage service.
   */
  public function __construct(StrakerTranslateProfileUsageInterface $profile_usage) {
    $this->profileUsage = $profile_usage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('straker_translate.profile_usage')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('straker_translate.settings');
  }

  /**
   * {@inheritDoc}
   */
  public function delete(array $form, FormStateInterface $form_state) {
    parent::delete($form, $form_state);
    $form_state->setRedirect('straker_translate.settings');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $profile = $this->getEntity();

    $usages = $this->profileUsage->isUsedByContent($profile) | $this->profileUsage->isUsedByConfig($profile) | $this->profileUsage->isUsedByContentSettings($profile);
    \Drupal::service('plugin.manager.straker_translate_form_bulk_action')->clearCachedDefinitions();
    if (!$usages) {
      $profile->delete();
      $this->messenger()->addStatus($this->t('The straker_translate profile %profile has been deleted.', ['%profile' => $profile->label()]));
    }
    else {
      $this->messenger()->addError($this->t('The Straker Translate profile %profile is being used so cannot be deleted.',
        ['%profile' => $profile->label()]));
    }

    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}
