<?php

namespace Ingot;

use Silex\Provider\MonologServiceProvider;
use Ingot\Provider\IngotServiceProvider;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

abstract class Application extends \Flint\Application
{
    protected $env;

    public function __construct($rootDir, $env, $debug = false, $parameters = [])
    {
        parent::__construct($rootDir, $debug, $parameters);

        $this['env'] = $env;
    }

    /**
     * Standardise the way we intialize service providers.
     */
    abstract protected function initialize();

    public function boot()
    {
        if ($this->booted) {
            return;
        }

        $this->register(new MonologServiceProvider);
        $this->register(new IngotServiceProvider);

        $this->initialize();

        // We ALWAYS have a configuration file
        $this->configure(__DIR__ . '/Resources/config/config.json');
        $this->configure('config/' . $this['env'] . '.json');

        // We want to setup the error handler according to the debug parameter
        // this converts fatal errors into exceptions
        ErrorHandler::register(null, false);

        parent::boot();
    }

    /**
     * {@inheritDoc}
     */
    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        if ($ip = $request->headers->get('X_REAL_IP')) {
            $request->server->set('REMOTE_ADDR', $ip);
        }

        if ('https' == $request->headers->get('X-Forwarded-Proto')) {
            $request->server->set('HTTPS', 'on');
        }

        return parent::handle($request, $type, $catch);
    }
}
