<?php

namespace Velis\Acl;

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

/**
 * ACL Application module model
 * @author Olek Procki <olo@velis.pl>
 */
class Module extends DataObject implements Cacheable
{
    protected static $_listDefaultOrder = "name_pl";


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


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


    /**
     * Returns string object representation
     * @return string
     */
    public function __toString()
    {
        return (self::hasField('acro') ? $this['acro'] : $this['app_module_id']) . ' - ' . $this->getName();
    }


    /**
     * Returns role acronym
     * @return string
     */
    public function getAcro()
    {
        return self::hasField('acro') ? $this['acro'] : $this['app_module_id'];
    }

    /**
     * Returns active modules
     * @return Module[]
     */
    public static function listActive()
    {
        $cached = self::listCached();

        return Arrays::byValue($cached, 'active', 1);
    }


    /**
    * Saves enabled/disabled modules
    * @param string|array module Id
    */
    public static function saveModuleSettings($modules)
    {
        if (!is_array($modules)) {
            $modules = [$modules];
        }

        $modulesCached = self::listCached();

        foreach ($modules as $key => $active) {
            $restore = self::$_db->checkDuplicatedQueries(false);
            $currModule = $modulesCached[$key] ?? self::instance($key);
            self::$_db->checkDuplicatedQueries($restore);

            if ($currModule) {
                $currModule['active'] = $active;
                $currModule->save();
            }
        }
    }
}
