<?php

namespace Tanzsport;

use Contao\BackendTemplate;
use Contao\Image;
use Contao\StringUtil;
use Contao\Widget;

class KartenWidget 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/tdKartenWidget.js";

        if (\Input::post('FORM_SUBMIT') == $this->strTable) {
            $this->varValue = \Input::post($this->strId);
        }

        if (!is_array($this->varValue) || count($this->varValue) == 0) {
            $this->varValue = array(array('preis' => '', 'text' => ''));
        }

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

        $arrCommands = array('copy', 'delete', 'drag', 'up', 'down');
        $arrButtons = array();
        foreach ($this->varValue as $i => $k) {
            $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 . '\');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["preis"]) && $arrEntry["preis"]) || (isset($arrEntry["text"]) && $arrEntry["text"])) {
                $empty = false;
            }
            if ($empty) {
                $remove[] = $i;
            }
        }
        foreach ($remove as $r) {
            unset($arrValue[$r]);
        }
        return serialize(array_values($arrValue));
    }
}
