<?php
/**
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application;

use Ainias\Core\Connections\MyConnection;
use Ainias\Core\Model\Doctrine\DatabaseListener;
use Doctrine\ORM\EntityManager;
use Zend\EventManager\Event;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Log\Filter\Priority;
use Zend\Log\Logger;
use Zend\Log\Writer\ChromePhp;
use Zend\Log\Writer\Stream;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Router\Http\TreeRouteStack;
use Zend\Session\Container;
use Zend\Session\SessionManager;
use Zend\View\Model\ViewModel;

class Module
{
    const VERSION = '3.0.0dev';
    const LOG_DIR = __DIR__ . "/../../../../log";
    const EVENT_LOG = "log";

    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        $request = $e->getRequest();

        $logPath = realpath(self::LOG_DIR);
        $logger = new Logger();
        $catchAllWriter = new Stream($logPath . "/log.log");
        $logger->addWriter($catchAllWriter);
        $errorWriter = new Stream($logPath . "/error.log");
        $errorWriter->addFilter(new Priority(Logger::ERR));
        $logger->addWriter($errorWriter);
        $errorLogger = new Logger();
        $phpErrorWriter = new Stream($logPath . "/php_error.log");
        $errorLogger->addWriter($catchAllWriter);
        $errorLogger->addWriter($phpErrorWriter);
        Logger::registerErrorHandler($errorLogger);
        Logger::registerFatalErrorShutdownFunction($errorLogger);

        $exceptionLogger = new Logger();
        $exceptionWriter = new Stream($logPath . "/php_exceptions.log");
        $exceptionLogger->addWriter($catchAllWriter);
        $exceptionLogger->addWriter($exceptionWriter);
        Logger::registerExceptionHandler($exceptionLogger);

        if (($request instanceof Request)) {
            $chromePhp = new ChromePhp();
            $errorLogger->addWriter($chromePhp);
            $exceptionLogger->addWriter($chromePhp);
        }

        $eventManager->getSharedManager()->attach('*', self::EVENT_LOG, function (Event $e) use ($logger) {
            $params = $e->getParams();

            if (isset($params["message"])) {
                if (isset($params["level"]) && ($params["level"] == Logger::ALERT || $params["level"] == Logger::CRIT || $params["level"] == Logger::DEBUG || $params["level"] == Logger::EMERG || $params["level"] == Logger::ERR || $params["level"] == Logger::INFO || $params["level"] == Logger::NOTICE)) {
                    $logLevel = $params["level"];
                } else {
                    $logLevel = Logger::INFO;
                }
                $logger->log($logLevel, $params["message"]);
            }
        });
    }

    public function getConfig()
    {
        $config = array();
        foreach (glob(__DIR__ . '/../config/*.config.php') as $filename) {
            $config = array_merge_recursive($config, include($filename));
        }
        return $config;
    }

//    public function getServiceConfig()
//    {
//        return [
//            'factories' => [
//                SessionManager::class => function ($container) {
//                    $config = $container->get('config');
//                    if (!isset($config['session'])) {
//                        $sessionManager = new SessionManager();
//                        Container::setDefaultManager($sessionManager);
//                        return $sessionManager;
//                    }
//
//                    $session = $config['session'];
//
//                    $sessionConfig = null;
//                    if (isset($session['config'])) {
//                        $class = isset($session['config']['class'])
//                            ? $session['config']['class']
//                            : SessionConfig::class;
//
//                        $options = isset($session['config']['options'])
//                            ? $session['config']['options']
//                            : [];
//
//                        $sessionConfig = new $class();
//                        $sessionConfig->setOptions($options);
//                    }
//
//                    $sessionStorage = null;
//                    if (isset($session['storage'])) {
//                        $class = $session['storage'];
//                        $sessionStorage = new $class();
//                    }
//
//                    $sessionSaveHandler = null;
//                    if (isset($session['save_handler'])) {
//                        // class should be fetched from service manager
//                        // since it will require constructor arguments
//                        $sessionSaveHandler = $container->get($session['save_handler']);
//                    }
//
//                    $sessionManager = new SessionManager(
//                        $sessionConfig,
//                        $sessionStorage,
//                        $sessionSaveHandler
//                    );
//
//                    Container::setDefaultManager($sessionManager);
//                    return $sessionManager;
//                },
//            ],
//        ];
//    }
}
