<?php

namespace Drupal\lingotek\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Configure Lingotek
 */
class LingotekUpdateAccessTokenForm extends LingotekConfigFormBase {

  /**
     * {@inheritdoc}
     */
  public function getFormID() {
    return 'lingotek.account_form';
  }

  /**
 * * {@inheritdoc}
     */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form = parent::buildForm($form, $form_state);
    $accountConfig = $this->config('lingotek.account');
    $host = $accountConfig->get('host');
    $auth_path = $accountConfig->get('authorize_path');
    $id = $accountConfig->get('default_client_id');
    $return_uri = $this->urlGenerator->generateFromRoute('lingotek.setup_account_handshake', ['success' => 'true', 'prod' => 'prod'], ['absolute' => TRUE]);
    $lingotek_connect_link = $host . '/' . $auth_path . '/' . $id . '?response_type=token&redirect_uri=' . urlencode($return_uri);

    $form['account']['access_token'] = [
    '#type'        => 'textfield',
    '#title'       => t('Access Token'),
    '#description' => t('The token currently used when communicating with the Lingotek service.'),
    ];

    $form['account_types']['existing_account']['cta'] = [
      '#type' => 'link',
      '#title' => $this->t('Generate new access token'),
      '#url' => Url::fromUri($lingotek_connect_link),
      '#attributes' => ['class' => ['lingotek_signup_box_cta', 'lingotek_signup_box_main_cta'],'target' => '_blank'],
    ];

    $form['actions']['submit']['#value'] = t('Save Token');

    $form['actions']['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelForm'],
      '#attributes' => ['class' => ['button']],
    ];
    return $form;
  }

  /**
     * {@inheritdoc}
     */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $access_token = \Drupal::request()->get("access_token");
    if (empty($access_token)) {
      $this->messenger()->addError($this->t('The access token is empty. Please provide a valid access token.'));
      return;
    }
    $form_state->setRedirect('lingotek.setup_account_handshake', ['access_token' => $access_token], []);
  }

  /**
   * {@inheritdoc}
   */
  public function cancelForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect('lingotek.settings');
  }


}
