<?php

declare(strict_types = 1);

namespace Drupal\background_slider\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure Background slider settings for this site.
 */
class SliderForm extends ConfigFormBase {

  /**
   * The form settings.
   *
   * @var \Drupal\Core\Form\ConfigFormBase
   */
  protected $settings;

  /**
   * Constructs for front page configuration.
   *
   * @param \Drupal\Core\Form\ConfigFormBase $config_factory
   *   A configuration array containing information about the plugin instance.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    parent::__construct($config_factory);
    $this->settings = 'background_slider.setting';
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'background_slider_setting';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'background_slider.setting',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config($this->settings);

    $form['background_slider'] = [
      '#type' => 'details',
      '#title' => $this->t('Front Page Slider'),
      '#open' => TRUE,
    ];

    $no_of_slides = $config->get("no_of_slides");
    $form['background_slider']['no_of_slides'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Number of slides'),
      '#default_value' => $no_of_slides,
      '#description'  => $this->t("Enter the number of slides required & click Apply."),
    ];

    $slider_type = $config->get("slider_type");
    $form['background_slider']['slider_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Slider type'),
      '#options' => [
        'select' => $this->t('Select'),
        'field_image' => $this->t('Slider image'),
        'field_video' => $this->t('Slider video'),
      ],
      '#default_value' => !empty($slider_type) ? $slider_type : '',
      '#ajax' => [
        'callback' => '::radioCallback',
        'wrapper' => 'type-wrapper',
        'event' => 'change',
        'method' => 'replace',
      ],
      '#description'  => $this->t("Select the field of slider type & click Apply."),
      '#open' => TRUE,
      '#attributes' => [
        'class' => ['form-control'],
      ],
    ];

    $form['background_slider']['button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Apply'),
      '#button_type' => 'primary',
      '#submit' => [[$this, 'submitFirstForm']],
    ];

    $form['background_slider']['slideshow']['#tree'] = TRUE;
    $form['background_slider']['slideshow'] = [
      '#type' => 'container',
      '#title' => $this->t('Slideshow Slider'),
      '#open' => TRUE,
      '#attributes' => [
        'id' => 'type-wrapper',
      ],
    ];

    for ($i = 1; $i <= $no_of_slides; $i++) {
      $form['background_slider']['slideshow']['slide'][$i] = [
        '#title' => 'Slide ' . $i,
        '#type' => 'fieldset',
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#attributes' => [
          'class' => ['form-control'],
        ],
      ];
      if ($config->get('slider_type', NULL) === "field_image") {

        $slide_image = $config->get("slide{$i}_image");
        $form['background_slider']['slideshow']['slide'][$i]['slide' . $i . '_image'] = [
          '#type' => 'managed_file',
          '#title' => $this->t('Slide @i @img', ['@i' => $i, '@img' => 'image']),
          '#description' => $this->t('Only ".gif, .png, .jpg, .jpeg, .webp files are allowed'),
          '#attributes' => [
            '#multiple' => TRUE,
          ],
          '#upload_validators' => [
            'file_validate_extensions' => ['gif png jpg jpeg webp'],
          ],
          '#default_value' => $slide_image,
          '#upload_location' => 'public://bk-imgs',
        ];
      }
      else {

        $slide_video = $config->get("slide{$i}_video");
        $form['background_slider']['slideshow']['slide'][$i]['slide' . $i . '_video'] = [
          '#type' => 'managed_file',
          '#title' => $this->t('Slide @i @vid', ['@i' => $i, '@vid' => 'Video']),
          '#description' => $this->t('Allowed extensions: mp4, m4v, mov, flv, f4v, ogg, ogv, wmv, vp6, vp5, mpg, avi, mpeg and webm'),
          '#attributes' => [
            '#multiple' => TRUE,
          ],
          '#upload_validators' => [
            'file_validate_extensions'  => ['mp4 m4v mov flv f4v ogg ogv wmv vp6 vp5 mpg avi mpeg webm'],
          ],
          '#default_value' => $slide_video,
          '#upload_location' => 'public://bk-videos',
        ];
      }
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitFirstForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config($this->settings);
    $config->set('no_of_slides', $form_state->getValue('no_of_slides'));
    $config->set('slider_type', $form_state->getValue('slider_type'));
    $config->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Short description of the code.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   *
   * @return mixed
   *   The return value description, if applicable.
   */
  public function radioCallback($form, FormStateInterface $form_state) {
    return $form['background_slider']['slideshow'];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config($this->settings);
    $form_values = $form_state->getValues();
    $no_of_slides = $config->get('no_of_slides', $form_values['no_of_slides']);
    $slide_type = $config->get('slider_type', $form_values['slider_type']);
    if ($slide_type == 'field_image') {
      for ($i = 1; $i <= $no_of_slides; $i++) {
        $config->set("slide{$i}_image", $form_values["slide{$i}_image"]);
        $image_fid = $config->get("slide{$i}_image");
        if (!empty($image_fid)) {
          $file = entityTypeManager()->getStorage('file')->load($image_fid[0]);
          $file->setPermanent();
          $file->save();
        }
      }
    }
    else {
      for ($i = 1; $i <= $no_of_slides; $i++) {
        $config->set("slide{$i}_video", $form_values["slide{$i}_video"]);
        $video_fid = $config->get("slide{$i}_video");
        if (!empty($video_fid)) {
          $file = entityTypeManager()->getStorage('file')->load($video_fid[0]);
          $file->setPermanent();
          $file->save();
        }
      }
    }
    $config->save();
    parent::submitForm($form, $form_state);
  }

}
