<?php

namespace Velis\Bpm\Ticket\Post;

use LogicException;
use ReflectionException;
use Velis\Arrays;
use Velis\Model\DataObject;
use Velis\App;
use Velis\Model\Cacheable;

/**
 * Ticket post template
 *
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 * @author Olek Procki <olo@velis.pl>
 */
class Template extends DataObject implements Cacheable
{

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


    /**
     * Returns template name
     * @return string
     */
    public function getName()
    {
        return $this->label;
    }


    /**
     * Templates list
     *
     * @param array|null $params
     * @param string|null $order
     * @param string|array|null $fields
     * @return Template[]
     * @throws ReflectionException
     */
    public static function listAll($params = null, $order = null, $fields = null)
    {
        if (App::$user->hasPriv('Ticket', 'PublicTemplateEdit') || $params['view']) {
            self::$_listConditions[] = "user_id IS NULL OR user_id=:user_id";
        } else {
            self::$_listConditions[] = "user_id=:user_id";
        }

        self::$_listParams['user_id'] = App::$user->id();

        return parent::listAll($params, $order, $fields);
    }


    /**
     * List cached templates for current user
     *
     * @param array $params
     * @return Template[]
     * @throws ReflectionException
     */
    public static function listCachedForUser($params)
    {
        $instance = new static();
        $cacheKey = $instance->_getListCacheName();

        if (!isset(App::$cache[$cacheKey])) {
            App::$cache[$cacheKey] = self::listAll(['view' => 1]);
        }

        $list = App::$cache[$cacheKey];

        if (!App::$user->hasPriv('Ticket', 'PublicTemplateEdit') || !$params['view']) {
            $list = Arrays::byValue($list, 'user_id', [App::$user->id()]);
        }

        return $list;
    }


    /**
     * Returns value name for cached list
     * @param bool $all
     * @return string
     */
    protected function _getListCacheName($all = false)
    {
        $cacheName = $this->_getListDatasource();
        if (strpos($cacheName, ' ')) {
            $cacheName = substr($cacheName, 0, strpos($cacheName, ' '));
        }
        if ($all) {
            return str_replace(array('.','_tab'), array('_',''), $cacheName) . '_list';
        }
        return str_replace(array('.','_tab'), array('_',''), $cacheName) . '_list' . App::$user->id();
    }


    /**
     * Unsets cache of objects list (Must implement Cacheable)
     * @throws LogicException
     */
    public static function unsetListCache()
    {
        $instance   = new static();

        if ($instance instanceof Cacheable) {
            $cacheMask = $instance->_getListCacheName(true);

            $cacheDir = DATA_PATH . 'cache/';
            foreach (glob($cacheDir . $cacheMask . '*') as $filename) {
                unlink($filename);
            }
        }

        parent::unsetListCache();
    }


    /**
     * Removes object from database
     * @return bool
     */
    public function remove()
    {
        return parent::_remove();
    }
}
