<?php
/**
 * Copyright (c) 2012-2021, Agence Française Informatique (AFI). All rights reserved.
 *
 * BOKEH is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
 * BOKEH is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with BOKEH; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
 */


class Intonation_View_RenderTimeline extends Intonation_View_Abstract_Layout {

  protected
    $_timeline_id,
    $_timeline_data = '';


  public function init() {
    $this->_timeline_id = 'timeline_' . uniqid();
  }


  public function renderTimeline($collection, $callback) {
    if ( $collection->isEmpty())
      return $this->_tagError($this->_('Aucun élément'));

    if ( ! $this->_timeline_data = $this->_renderTimelineJSON($collection, $callback))
      return $this->_tagError($this->_('Pas de date disponible'));

    $this->renderHeadScriptsOn(Class_ScriptLoader::getInstance());

    $script_loader = (new Class_ScriptLoader)
          ->addJQueryReady(sprintf('new TL.Timeline("%s", %s, %s);',
                               $this->_timeline_id,
                               $this->_timeline_data,
                               json_encode(['font' => null,
                                            'width' => '100%',
                                            'start_at_end' => true,
                                            'lang' => 'fr'])));
    return $script_loader->html()
      . $this->_div(['id' => $this->_timeline_id]);
  }



  public function renderHeadScriptsOn($script_loader) {
    parent::renderHeadScriptsOn($script_loader);
    $script_loader
      ->addScript(Class_Url::relative('/library/templates/Intonation/Assets/timeline3/js/timeline.js'))
      ->addStyleSheet(Class_Url::relative('/library/templates/Intonation/Assets/timeline3/css/timeline.css'))
      ->addStyleSheet(Class_Url::relative('/library/templates/Intonation/Assets/timeline3/css/bokeh_timeline.css'));
  }


  protected function _renderTimelineJSON($collection, $callback) {
    return ($events = array_filter($this->_renderEvents($collection, $callback)))
      ? json_encode(['events' => $events])
      : '';
  }


  protected function _renderEvents($collection, $callback) {
    return
      $collection->injectInto([],
                              function($events, $element) use ($callback)
                              {
                                if ($event = $this->_renderEvent($element, $callback))
                                  $events [] = $event;
                                return $events;
                              });
  }


  protected function _renderEvent($element, $callback) : array {
    $events_dates = $element->getTimelineEventsDates();
    $start_date = (array) $events_dates->getStartDate();

    if ( (! isset($start_date['year'])) || ( ! $start_date['year']))
      return [];

    $picture_url = (string) $element->getPicture();

    $datas = ['start_date' => $start_date,

              'text' => ['headline' => $this->_getHeadline($element),
                         'text' => (string) $callback($element)],

              'media' => ['thumbnail' => $picture_url,
                          'url' => $picture_url],

              'unique_id' => uniqid() . '_' . $element->getId()];

    if ( isset($end_date['year']) && ($end_date = $end_date['year']))
      $datas ['end_date'] = $end_date;

    return $datas;
  }


  protected function _getHeadline($element) : string {
    return (string) $this->view->truncate($element->getMainTitle(),
                                          [],
                                          3,
                                          false,
                                          '');
  }
}