<?php

namespace Drupal\straker_translate\Form;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\straker_translate\Exception\StrakerTranslateApiException;
use Drupal\straker_translate\StrakerTranslateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure Straker Translate.
 */
class StrakerTranslateSettingsTabAccountForm extends StrakerTranslateConfigFormBase {

  /**
   * Constructs a StrakerTranslateSettingsTabAccountForm 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\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, UrlGeneratorInterface $url_generator = NULL, LinkGeneratorInterface $link_generator = NULL) {
    parent::__construct($straker_translate, $config, $url_generator, $link_generator);
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $accountConfig = $this->config('straker_translate.account');

    $connectionStatus = $this->t('Inactive');

    try {
      if ($this->straker_translate->getAccountInfo()) {
        $connectionStatus = $this->t('Active');
      }
    }
    catch (StrakerTranslateApiException $exception) {
      $this->messenger()->addWarning($this->t('There was a problem checking your account status.'));
    }

    $statusRow = [
      ['#markup' => $this->t('Status:'), '#prefix' => '<b>', '#suffix' => '</b>'],
      ['#markup' => $connectionStatus],
      ['#markup' => ''],
    ];
    $tokenRow = [
      ['#markup' => $this->t('Access Token:'), '#prefix' => '<b>', '#suffix' => '</b>'],
      ['#markup' => '************************************'],
      ['#markup' => $this->linkGenerator->generate($this->t('Update token'), Url::fromRoute('straker_translate.access_token_update'))],
    ];

    $resources = $this->straker_translate->getResources();

    $default_workflow = $accountConfig->get('default.workflow');

    if ($default_workflow === 'project_default') {
      $default_workflow_name = $this->t('Project Default');
    }
    else {
      $default_workflow_name = $resources['workflow'][$default_workflow] ?? '';
    }

    $workflowRow = [
      ['#markup' => $this->t('Default Workflow:'), '#prefix' => '<b>', '#suffix' => '</b>'],
      ['#markup' => new FormattableMarkup('@name (@id)', ['@name' => $default_workflow_name, '@id' => $default_workflow])],
      ['#markup' => $this->linkGenerator->generate($this->t('Edit defaults'), Url::fromRoute('straker_translate.edit_defaults'))],
    ];

    $default_project = $accountConfig->get('default.project');
    $default_project_name = $resources['project'][$default_project] ?? '';
    $projectRow = [
      ['#markup' => $this->t('Default Project:'), '#prefix' => '<b>', '#suffix' => '</b>'],
      ['#markup' => new FormattableMarkup('@name (@id)', ['@name' => $default_project_name, '@id' => $default_project])],
      ['#markup' => $this->linkGenerator->generate($this->t('Edit defaults'), Url::fromRoute('straker_translate.edit_defaults'))],
    ];

    $tmsRow = [
      ['#markup' => $this->t('Straker Translate API:'), '#prefix' => '<b>', '#suffix' => '</b>'],
      ['#markup' => $accountConfig->get('host')],
      ['#markup' => ''],
    ];
    $domainRow = [
      ['#markup' => $this->t('Straker Translate Server:'), '#prefix' => '<b>', '#suffix' => '</b>'],
      ['#markup' => $accountConfig->get('domain')],
      ['#markup' => ''],
    ];

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

    $accountTable['status_row'] = $statusRow;
    $accountTable['token_row'] = $tokenRow;
    $accountTable['workflow_row'] = $workflowRow;
    $accountTable['tms_row'] = $tmsRow;
    $accountTable['domain_row'] = $domainRow;

    $form['account'] = [
      '#type' => 'details',
      '#title' => $this->t('Account'),
    ];

    $form['account']['account_table'] = $accountTable;
    $form['account']['actions']['#type'] = 'actions';
    $form['account']['actions']['disconnect'] = [
      '#type' => 'submit',
      '#value' => $this->t('Disconnect'),
      '#button_type' => 'danger',
      '#submit' => [[$this, 'disconnect']],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function disconnect(array &$form, FormStateInterface $form_state) {
    // Redirect to the confirmation form.
    $form_state->setRedirect('straker_translate.account_disconnect');
  }

}
