<?php

namespace ArcaSolutions\WebBundle\Repository;

use ArcaSolutions\WebBundle\Entity\Setting;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr;

/**
 * SettingRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
final class SettingRepository extends EntityRepository
{
    /**
     * @var array
     */
    private $settings = [];

    /**
     * It is the pattern that is followed by DB to represent module
     * @var string
     */
    private $module_placeholder = 'custom_%s_feature';

    /**
     * @param $key
     *
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     * @throws \Exception
     */
    public function getSetting($key)
    {
        if (!array_key_exists($key, $this->settings)) {
            /* @var $setting Setting */
            $setting = $this->findOneBy(["name" => "$key"]);
            $this->settings[$key] = $setting ? $setting->getValue() : null;
        }

        return $this->settings[$key];
    }

    /**
     * It checks if the modules passed by are available
     *
     * @param array $modules_name
     * @return array
     */
    public function whichModulesAreAvailable($modules_name = [])
    {
        /* removes listing from array because listing is always enabled */
        $key_listing = array_search('listing', $modules_name);
        if (is_int($key_listing)) {
            unset($modules_name[$key_listing]);
        }

        /* builds setting keys */
        $keys_setting = [];
        foreach ($modules_name as $item) {
            $keys_setting[$item] = sprintf($this->module_placeholder, $item);
        }

        /* fetching modules settings */
        $query = $this->createQueryBuilder('modules');
        $inExpr = $query->expr()->in('modules.name', $keys_setting);
        $rows = $query->where($inExpr)->getQuery()->getResult();

        /* @var $row Setting */
        /* turns values into keys and sets null as value */
        $modules_available = array_fill_keys($modules_name, null);
        foreach ($rows as $row) {
            $key = array_search($row->getName(), $keys_setting);
            $modules_available[$key] = $row->getValue() ? true : false;
        }
        /* listing is always enabled */
        $modules_available['listing'] = true;

        return $modules_available;
    }

    /**
     * It checks if module is enabled
     *
     * @param string $module
     * @return bool
     */
    public function isModuleAvailable($module = '')
    {
        /* listing is always enabled */
        if ('listing' == $module) {
            return true;
        }

        /* @var $row Setting */
        try {
            $row = $this->getSetting(sprintf($this->module_placeholder, $module));
        } catch (\Exception $e) {
            $row = false;
        }

        return $row && $row == 'on' ? true : false;
    }
}
