<?php

namespace Velis\Mvc\View\Helper;

use Velis\Bpm\Ticket\Post;
use Velis\Bpm\Ticket\Post\Checklist\Item;
use Velis\Filter;
use Velis\Output;

/**
 * Checklist renderer helper
 * @author Olek Procki <olo@velis.pl>
 */
class Checklist
{
    /**
     * Related checklist post
     * @var Post
     */
    protected $_post;


    /**
     * Returns script include HTML
     * @param Post|Item[] $data
     * @return string
     */
    public function __invoke($data)
    {
        if ($data instanceof Post) {
            // get root checklist elements
            $source = $data->getChecklistItemsByParentId();
            $this->_post = $data;
        } else {
            $source = $data;
        }

        if (!$source) {
            return '';
        }

        $html = '';

        if ($data instanceof Post) {
            $html .= '<div class="checklist" id="checklist' . $data->id() . '" data-id="' . $data->id() . '">'
                . '<div data-dojo-type="dijit/ProgressBar" id="checklistProgressBar' . $data->id() . '"></div>';
        }

        $html .= '<ol';
        if (!$data instanceof Post) {
            $html .= ' type="a"';
        }
        $html .= '>';

        foreach ($source as $item) {
            $children = $this->_post->getChecklistItemsByParentId($item->id());

            $html .= '<li class="item' . $item->id()
                . ($item->is_closed ? ' inactive' : '')
                . ($children ? '' : ' checklistLeaf') . '">';

            $html .= '<div style="margin-bottom: 3px" class="checklist-title' . ($item->is_closed ? ' inactive' : '') . '">';
            $html .= '<input type="checkbox" class="cbx" id="chl' . $item->id() . '" data-id="' . $item->id() . '"'
                . ($item->is_closed ? 'checked="checked"' : '')
                . ' data-dojo-type="dijit/form/CheckBox">&nbsp;';
            $html .= preg_replace("~</?p>~", "", Output::changeLinks(Filter::filterTextile(trim($item->getName()))));
            $html .= '</div>';

            if ($children) {
                $html .= $this($children);
            }

            $html .= '</li>';
        }

        $html .= '</ol>';
        if ($data instanceof Post) {
            $html .= '</div>';
        }

        return $html;
    }
}
