<?php


namespace Zeedhi\Framework\DBAL\Driver;


use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\DBAL\Events;
use Zeedhi\Framework\DependencyInjection\InstanceManager;

class SQLSessionInit extends \Doctrine\DBAL\Event\Listeners\SQLSessionInit
{

    /** @var string[] */
    protected $_defaultSessionVars = [];

    protected $langNlsNumericChar = [
        'en' => '.,',
        'pt' => ',.',
        'es' =>'.,',

    ];

    public function getDefaultSessionVars()
    {
        return $this->_defaultSessionVars;
    }

    /**
     * @return void
     */
    public function postConnect(ConnectionEventArgs $args)
    {
        if (! count($this->_defaultSessionVars)) {
            return;
        }

        /** @var \Doctrine\DBAL\Event\Listeners\OracleSessionInit $sessionInit */
        $nlsNumericCharDynamic = InstanceManager::getInstance()->getParameter('nlsNumericCharDynamic');
        if ($nlsNumericCharDynamic) {
            /** @var \Zeedhi\Framework\Session\Session $sessionInit */
            $session = \Zeedhi\Framework\DependencyInjection\InstanceManager::getInstance()->getService('session');
            $loginLanguage = $session->has("LOGIN_LANGUAGE") ? $session->get("LOGIN_LANGUAGE") : '';
            $language = explode('_',$loginLanguage)[0];
            if(!empty($this->langNlsNumericChar[$language])){
                $nlsNumericCharacters = $this->langNlsNumericChar[$language];
                $this->_defaultSessionVars['NLS_NUMERIC_CHARACTERS'] = $nlsNumericCharacters;
            }
        }

        $vars = [];
        foreach (array_change_key_case($this->_defaultSessionVars, CASE_UPPER) as $option => $value) {
            if ($option === 'CURRENT_SCHEMA') {
                $vars[] = $option . ' = ' . $value;
            } else {
                $vars[] = $option . " = '" . $value . "'";
            }
        }

        $sql = 'ALTER SESSION SET ' . implode(' ', $vars);
        $args->getConnection()->executeStatement($sql);
    }

    /**
     * {@inheritdoc}
     */
    public function getSubscribedEvents()
    {
        return [Events::postConnect];
    }
}
