<?php

namespace Velis\Bpm\Ticket\Post\Checklist;

use Velis\Bpm\Ticket\Post;
use Velis\Filter;
use Velis\Model\Hierarchical;

/**
 * Checklist item model
 * @author Olek Procki <olo@velis.pl>
 */
class Item extends Hierarchical
{
    /**
     * Default list order
     * @var string
     */
    protected static $_listDefaultOrder = 'ticket_post_checklist_id';


    /**
     * Related ticket post
     * @var Post
     */
    protected $_post;


    /**
     * Returns related table name
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.ticket_post_checklist_tab';
    }


    /**
     * Returns list datasource view
     * @return string
     */
    protected function _getListDatasource()
    {
        return 'app.ticket_post_checklist tpc';
    }


    /**
     * Returns parent item id
     * @return int
     */
    public function getParentId()
    {
        return $this->parent_ticket_post_checklist_id;
    }


    /**
     * Compares categories names - dedicated for sorting collections
     *
     * @param Hierarchical $element1
     * @param Hierarchical $element2
     *
     * @return int
     */
    public static function compareNames(Hierarchical $element1, Hierarchical $element2)
    {
        return strcasecmp($element1->id(), $element2->id());
    }


    /**
     * Converts to string
     * @param bool $html
     * @return string
     */
    public function output($html = false)
    {
        $output = '#' . str_repeat("#", $this['level']) . ' ';

        if ($this->is_closed) {
            $output .= '-';
        }

        if ($html) {
            $output .= htmlspecialchars($this->getName());
        } else {
            $output .= $this->getName();
        }

        if ($this->is_closed) {
            $output .= '-';
        }

        if ($html) {
            return Filter::filterTextile($output);
        } else {
            return $output;
        }
    }


    /**
     * Returns related ticket post
     * @return Post
     */
    public function getPost()
    {
        if (!isset($this->_post)) {
            $this->_post = Post::instance($this['ticket_post_id']);
        }

        return $this->_post;
    }
}
