<?php

namespace Drupal\straker_translate\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteBuilderInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\straker_translate\StrakerTranslateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Tab for running Straker Translate utilities in the settings page.
 */
class StrakerTranslateSettingsTabUtilitiesForm extends StrakerTranslateConfigFormBase {

  /**
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * The route builder service.
   *
   * @var \Drupal\Core\Routing\RouteBuilderInterface
   */
  protected $routeBuilder;

  /**
   * Constructs a \Drupal\straker_translate\Form\StrakerTranslateSettingsTabUtilitiesForm object.
   *
   * @param \Drupal\straker_translate\StrakerTranslateInterface $straker_translate
   *   The straker_translate service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
   *   The factory for configuration objects.
   * @param \Drupal\Core\State\StateInterface $state
   *   The state key/value store.
   * @param \Drupal\Core\Routing\RouteBuilderInterface $route_builder
   *   The route builder service.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The url generator.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The link generator.
   */
  public function __construct(StrakerTranslateInterface $straker_translate, ConfigFactoryInterface $config, StateInterface $state, RouteBuilderInterface $route_builder, UrlGeneratorInterface $url_generator = NULL, LinkGeneratorInterface $link_generator = NULL) {
    parent::__construct($straker_translate, $config, $url_generator, $link_generator);
    $this->state = $state;
    $this->routeBuilder = $route_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('straker_translate'),
      $container->get('config.factory'),
      $container->get('state'),
      $container->get('router.builder'),
      $container->get('url_generator'),
      $container->get('link_generator')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'straker_translate.settings_tab_utilities_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $accountConfig = $this->configFactory()->get('straker_translate.account');
    $form['utilities'] = [
      '#type' => 'details',
      '#title' => $this->t('Utilities'),
    ];

    $straker_translate_table = [
      '#type' => 'table',
      '#empty' => $this->t('No Entries'),
    ];

    // Refresh resources via API row.
    $api_refresh_row = [];
    $api_refresh_row['refresh_description'] = [
      '#markup' => '<h5>' . $this->t('Refresh Workflow Information') . '</h5>' . '<p>' . $this->t('This module locally caches the available workflows. Use this utility whenever you need to pull down names for any newly created workflows from the  Straker Translate.') . '</p>',
    ];
    $api_refresh_row['actions']['refresh_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Refresh'),
      '#button_type' => 'primary',
      '#submit' => ['::refreshResources'],
    ];

    // Disassociate All Translations row.
    $disassociate_row = [];
    $disassociate_row['disassociate_description'] = [
      '#markup' => '<h5>' . $this->t('Disassociate All Translations (use with caution)') . '</h5>' . '<p>' . $this->t('Should only be used to change the Straker associated with the node’s translation. Option to disassociate node translations on Straker servers from the copies downloaded to Drupal. Additional translation using Straker will require re-uploading the node’s content to restart the translation process.') . '</p>',
    ];

    $disassociate_row['actions']['#type'] = 'actions';
    $disassociate_row['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Disassociate'),
      '#submit' => ['::disassociateAllTranslations'],
      '#attributes' => [
        'class' => ['button', 'button--danger'],
      ],
    ];

    $debug_enabled = $this->state->get('straker_translate.enable_debug_utilities', FALSE);
    $enable_debug_utilities_row = [];
    $enable_debug_utilities_row['enable_debug_utilities_description'] = [
      '#markup' => '<h5>' . $this->t('Debug utilities') . '</h5>' . '<p>' . $this->t('Debug the Content entities metadata') . '</p>',
    ];
    $enable_debug_utilities_row['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $debug_enabled ? $this->t('Disable debug operations') : $this->t('Enable debug operations'),
      '#button_type' => 'primary',
      '#submit' => ['::switchDebugUtilities'],
    ];

    $straker_translate_table['api_refresh'] = $api_refresh_row;
    $straker_translate_table['disassociate'] = $disassociate_row;
    $straker_translate_table['enable_debug_utilities'] = $enable_debug_utilities_row;

    $form['utilities']['straker_translate_table'] = $straker_translate_table;

    return $form;
  }

  /**
   *
   */
  public function switchDebugUtilities() {
    $value = $this->state->get('straker_translate.enable_debug_utilities', FALSE);
    $this->state->set('straker_translate.enable_debug_utilities', !$value);
    $this->routeBuilder->rebuild();
    $this->messenger()->addStatus($this->t('Debug utilities has been %enabled.', ['%enabled' => !$value ? $this->t('enabled') : $this->t('disabled')]));
  }

  /**
   * Submit handler for refreshing the resources: projects, workflows, vaults,
   * and filters.
   */
  public function refreshResources() {
    \Drupal::cache()->delete('straker_translate.workflows');
    $resources = $this->straker_translate->getResources(TRUE);
    $this->messenger()->addStatus($this->t('Workflow information have been refreshed.'));
  }

  /**
   *
   */
  public function disassociateAllTranslations(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect('straker_translate.confirm_disassociate');
  }

}
