<?php

namespace Velis\Bpm\Email;

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

/**
 * Email footer model
 *
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 */
class Footer extends DataObject implements Cacheable
{
    /**
     * Returns related sql table
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.email_footer_tab';
    }

    /**
     * Removes footer
     */
    public function remove()
    {
        $this->_remove();
    }


    /**
     * get name of object
     * @return string
     */
    public function getName()
    {
        return $this['name'];
    }


    /**
     * set footer as default
     */
    public function setDefault()
    {
        $footers = self::listAll(array('user_id' => $this->user_id));

        foreach ($footers as $footer) {
            if ($footer['is_default'] == 1 && $footer->id() != $this->id()) {
                $footer['is_default'] = 0;
                $footer->modify();
            }
        }
    }

    /**
     * Returns value name for cached list
     * @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();
    }


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

        if (!isset(App::$cache[$cacheKey])) {
            App::$cache[$cacheKey] = self::listAll(['user_id' => App::$user->id()]);
        }

        return App::$cache[$cacheKey];
    }


    /**
     * 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();
    }
}
