<?php

namespace Drupal\background_slider\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'sliderblock' block.
 *
 * @Block(
 *   id = "slider_block",
 *   admin_label = @Translation("Slider Block"),
 *   category = @Translation("Custom Slider Block")
 * )
 */
class SliderBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    global $base_url;
    $module_path = $base_url . '/' . service('extension.list.module')->getPath('background_slider');

    $form = formBuilder()->getForm('Drupal\background_slider\Form\SliderForm');

    $slider_content = [];
    $config = config('background_slider.setting');
    $no_of_slides = $config->get('no_of_slides');
    $slider_type = $config->get('slider_type');

    for ($i = 1; $i <= $no_of_slides; $i++) {

      $slider_image_fid = $config->get("slide{$i}_image");
      $slider_url = "";
      if (!empty($slider_image_fid)) {
        $slider_image_obj = load($slider_image_fid[0]);
        $uri = $slider_image_obj->getFileUri();
        $slider_url = service('file_url_generator')->generateAbsoluteString($uri);
      }

      $slider_video_fid = $config->get("slide{$i}_video");
      $video_path = "";
      if (!empty($slider_video_fid)) {
        $slider_video_obj = load($slider_video_fid[0]);
        $uri = $slider_video_obj->getFileUri();
        $video_path = service('file_url_generator')->generateAbsoluteString($uri);
      }

      if ($slider_type == 'field_image') {
        $slider_content[$i] = '<img src="' . $slider_url . '" alt="Slider Images" class="d-block" style="width:100%" />';
      }
      else {
        $slider_content[$i] = '<video class ="d-block" autoplay loop muted style="width:100%; height:auto;">
																<source src="' . $video_path . '" type="video/mp4" />
															</video>';
      }
    }

    return [
      '#theme' => 'block__slider_block',
      '#form' => $form,
      'slider_content' => $slider_content,
      '#module_path' => $module_path,
      '#attached' => [
        'library' => [
          'background_slider/slider-style',
        ],
      ],
    ];
  }

}
