<?php

namespace Velis\Bpm\Ticket;

use Velis\Arrays;
use Velis\Exception;
use Velis\Lang;
use Velis\Model\Cacheable;
use Velis\Model\DataObject;
use Velis\Model\Hierarchical;

/**
 * Ticket status class
 * @author Olek Procki <olo@velis.pl>
 */
class Status extends DataObject implements Cacheable
{
    /**
     * Buffer for not cached model type (must be redeclared in Cachable class)
     * @var Hierarchical[]
     */
    protected static $_source;


    protected static $_listAssocKey = false;


    /**
     * Default status list ordering
     * @var string
     */
    protected static $_listDefaultOrder = 'ticket_type_sort_order, sort_order, ticket_closed, name_pl';


    /**
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.ticket_status_tab';
    }


    /**
     * @return string
     */
    protected function _getListDatasource()
    {
        return 'app.ticket_status';
    }


    /**
     * Returns status name
     * @return ?string
     */
    public function getName(): ?string
    {
        return $this->getTranslatedName();
    }


    /**
     * Returns status info
     * @return string
     */
    public function __toString()
    {
        $desc = $this->getTranslatedName();
        if (strlen($this->progress_percent)) {
            $desc .= " (" . $this->progress_percent . "%)";
        }
        return $desc;
    }


    /**
     * Returns statuses by ticket type
     *
     * @param string $type
     * @return Status[]
     */
    public static function byType($type)
    {
        $statuses = array();
        foreach (self::listCached() as $status) {
            if ($status->ticket_type_id == $type) {
                $statuses[$status->id()] = $status;
            }
        }

        return $statuses;
    }


    /**
     * Return statuses not marked as closed
     *
     * @param bool $simple Return object list or simple id array
     * @return Status[]|string[]
     * @throws Exception
     */
    public static function getOpenStatuses($simple = false)
    {
        $statuses = array();
        foreach (self::listCached() as $statusId => $status) {
            if (!$status->ticket_closed) {
                $statuses[$statusId] = $status;
            }
        }
        if ($simple) {
            return array_unique(Arrays::getColumn($statuses, 'ticket_status_id'));
        } else {
            return $statuses;
        }
    }


    /**
     * Returns true if status is available
     * @param mixed $status
     * @param string $type
     *
     * @return bool
     */
    public static function isAvailable($status, $type)
    {
        if (!$status instanceof self) {
            $status = new self($status);
        }

        return $status->belongs(self::byType($type));
    }

    public function isClosed(): bool
    {
        return $this->ticket_closed == 1;
    }
}
