<?php

namespace Tanzsport;

use Contao\StringUtil;
use Contao\Widget;

class TurnierzeitenWidget extends Widget
{

    /**
     * Submit user input
     * @var boolean
     */
    protected $blnSubmitInput = true;

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

    public function __construct($arrAttributes = null)
    {
        parent::__construct($arrAttributes);
    }

    /**
     * Generate the widget and return it as string
     *
     * @return string The widget markup
     */
    public function generate()
    {
        $GLOBALS['TL_JAVASCRIPT'][] = "bundles/contaoformationen/js/widgets/tdTurnierzeitenWidget.js";

        if (\Input::post('FORM_SUBMIT') == $this->strTable) {
            $this->varValue = \Input::post($this->strId);
        } else {
            if (!is_array($this->varValue) || empty($this->varValue)) {
                $this->varValue = array(array('uhrzeit' => '', 'text' => ''));
            }
        }

        $template = new \BackendTemplate('widget_turnierzeiten');
        $template->strId = $this->strId;
        $template->value = $this->varValue;

        $arrCommands = array('copy', 'delete', 'drag', 'up', 'down');
        $arrButtons = array();
        foreach ($this->varValue as $i => $z) {
            $arrButtons[$i] = array();
            foreach ($arrCommands as $button) {
                $class = ($button == 'up' || $button == 'down') ? ' class="button-move"' : '';
                if ($button == 'drag') {
                    $arrButtons[$i][] = \Image::getHtml('drag.gif', '', 'class="drag-handle" title="' . sprintf($GLOBALS['TL_LANG']['MSC']['move']) . '"');
                } else {
                    $arrButtons[$i][] = '<a href="#"' . $class . ' title="' . specialchars($GLOBALS['TL_LANG']['MSC']['mw_' . $button]) . '" onclick="tdTurnierzeitenWidget.doCommand(this,\'' . $button . '\',\'ctrl_' . $this->strId . '_zeitplan\');return false">' . \Image::getHtml($button . '.gif', $GLOBALS['TL_LANG']['MSC']['mw_' . $button], 'class="tl_listwizard_img"') . '</a>';
                }
            }
        }
        $template->buttons = $arrButtons;

        return $template->parse();
    }

    protected function validator($varInput)
    {
        return parent::validator($varInput);
    }

    public static function saveCallback($value, \DataContainer $dc)
    {
        $arrValue = StringUtil::deserialize($value, true);
        $remove = array();
        foreach ($arrValue as $i => $arrEntry) {
            $empty = true;
            if (isset($arrEntry["uhrzeit"]) && $arrEntry["text"]) {
                $empty = false;
            }
            if ($empty) {
                $remove[] = $i;
            }
        }
        foreach ($remove as $r) {
            unset($arrValue[$r]);
        }
        if (empty($arrValue)) {
            return null;
        } else {
            return serialize($arrValue);
        }
    }

}
