<?php

/**
 * Slick slider for Contao
 *
 * Copyright (c) 2016 Benjamin Roth
 *
 * @license LGPL-3.0+
 */

namespace EsalesMedia\ContaoSwiperBundle\Frontend\Element;

/**
 * Front end content element swiper image slide.
 */
class ContentSwiperSliderImage extends \ContentElement
{

	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'ce_swiper_slider_image';

  /**
   * @return string
   */
  public function generate()
  {
    if (TL_MODE == 'BE')
    {
      $return = '';

      if ($this->multiSRC)
      {

        $source = \StringUtil::deserialize($this->multiSRC);
        $objFiles = \FilesModel::findMultipleByUuids($source);

        if ($objFiles !== null)
        {
          foreach ($objFiles as $file)
          {
            if (is_file(TL_ROOT . '/' . $file->path))
            {
              if (in_array($file->extension, array_map('trim', explode(',', \Config::get('validImageTypes')))))
              {
                $src = \System::getContainer()->get('contao.image.image_factory')->create(TL_ROOT . '/' . $file->path, array(66, 55, 'crop'))->getUrl(TL_ROOT);
                $return .= '<img src="' . $src . '">'."\n";
              } else if (in_array($file->extension, array_map('trim', array('mp4', 'm4v', 'mov', 'wmv', 'webm', 'ogv', 'm4a', 'mp3', 'wma', 'mpeg', 'wav', 'ogg')))) {
                $return .= '<span>'.$GLOBALS['TL_LANG']['tl_content']['singleSRC'][0].': <a href="'.$file->path.'" target="_blank">'.$file->name.'</a></span>'."\n";
              }
            }
          }
        }
      }

      return $return;
    }

    $parentKey = ($this->arrData['ptable'] ?: 'tl_article') . '__' . $this->arrData['pid'];

    if (isset($GLOBALS['TL_ESM_SLICK'][$parentKey]))
    {
      $this->arrData['parentSlickId'] = $GLOBALS['TL_ESM_SLICK'][$parentKey];
    } else {
      $this->arrData['parentSlickId'] = 0;
    }


    return parent::generate();
  }

  /**
   * Generate the content element
   */
  protected function compile()
  {
    if (TL_MODE == 'BE')
    {
      $this->strTemplate = 'be_wildcard';

      /** @var \BackendTemplate|object $objTemplate */
      $objTemplate = new \BackendTemplate($this->strTemplate);

      $this->Template = $objTemplate;
    }

    if ($this->multiSRC)
    {

      $source = \StringUtil::deserialize($this->multiSRC);
      $objFiles = \FilesModel::findMultipleByUuids($source);

      $imageFiles = array();
      $videoFiles = array();

      if ($objFiles !== null) {

        foreach ($objFiles as $file) {
          if (is_file(TL_ROOT . '/' . $file->path))
          {
            if (in_array($file->extension, array_map('trim', explode(',', \Config::get('validImageTypes')))))
            {
              $imageFiles[] = $file;
            } else if (in_array($file->extension, array_map('trim', array('mp4', 'm4v', 'mov', 'wmv', 'webm', 'ogv', 'm4a', 'mp3', 'wma', 'mpeg', 'wav', 'ogg'))))
            {
              $videoFiles[] = $file;
            }
          }
        }
      }

      if (isset($imageFiles[0]))
      {
        $this->singleSRC = $imageFiles[0]->path;

        $this->addImageToTemplate($this->Template, array('singleSRC'=>$this->singleSRC, 'size'=>$this->size));

        $backgroundStyle = '';

        if ($this->eSM_slider_minHeight) {
          if ($this->eSM_slider_bgSize && $this->eSM_slider_bgSize == 'auto auto') {
            $minHeight = $this->Template->picture['img']['height'] . 'px';
          } else
          {
            $minHeight = round($this->Template->picture['img']['height'] / $this->Template->picture['img']['width'] * 100) . '%';
          }
          $backgroundStyle .= '.slide_'.$this->id.':before { content: ""; display: block; float: left; padding-top: '.$minHeight.'; }';
        }


        $backgroundStyle .= '.slide_'.$this->id.' .swiper-slide-image { background-image: url(\''.$this->Template->src.'\');';

        if ($this->eSM_slider_bgSize) {
          $backgroundStyle .= 'background-size: ' . $this->eSM_slider_bgSize . ';';
        } else {
          $backgroundStyle .= 'background-size: cover;';
        }
        if ($this->eSM_slider_bgPosition) {
          $backgroundStyle .= 'background-position: ' . $this->eSM_slider_bgPosition . ';';
        } else {
          $backgroundStyle .= 'background-position: 0 0;';
        }
        if ($this->eSM_slider_bgOpacity) {
          $backgroundStyle .= 'opacity:' . $this->eSM_slider_bgOpacity/100 . ';';
        }
        if ($this->eSM_slider_bgRepeat) {
          $backgroundStyle .= 'background-repeat: ' . $this->eSM_slider_bgRepeat . ';';
        }

        $this->Template->backgroundStyle = $backgroundStyle.' }';

        // Responsive handling
        if ($this->Template->picture['sources'] && is_array($this->Template->picture['sources']))
        {
          $backgroundStyleResponsive = '';
          foreach ($this->Template->picture['sources'] as $srcSet)
          {
            $srcSetStyle = '.slide_'.$this->id.' .swiper-slide-image { background-image: url(\''.$srcSet['src'].'\'); }';

            if ($this->eSM_slider_minHeight) {
              if ($this->eSM_slider_bgSize && $this->eSM_slider_bgSize == 'auto auto') {
                $minHeight = $srcSet['height'] . 'px';
              } else
              {
                $minHeight = round($srcSet['height'] / $srcSet['width'] * 100) . '%';
              }
              $srcSetStyle .= '.slide_'.$this->id.':before { content: ""; display: block; float: left; padding-top: '.$minHeight.'; }';
            }

            $backgroundStyleResponsive .= '@media screen and '.$srcSet['media'].' { '.$srcSetStyle.' }';
          }
          $this->Template->backgroundStyleResponsive = $backgroundStyleResponsive;
        }

      }

      if (count($videoFiles)) {
        $this->Template->videoFiles = $videoFiles;
      }
    }

    if ($this->eSM_slider_addImageLink)
    {
      $this->Template->lightboxId = 'image_slide_' . ($this->parentSlickId ?: 's'.$this->id);
      $this->Template->fullsize = $this->fullsize;
      $this->Template->imageLink = ($this->imageUrl ?: $this->singleSRC);
    }

    if ($this->eSM_addText)
    {
      $this->Template->text = nl2br($this->eSM_slider_text);
      $this->Template->link = $this->eSM_slider_url;
    }

  }

}
