<?php
/**
 * Created by PhpStorm.
 * User: giangnguyen
 * Date: 10/7/14
 * Time: 10:53 PM
 */

use Adrotec\BreezeJs\Framework\StandaloneApplication;
use Adrotec\BreezeJs\Framework\ResourceNotFoundException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class OilApplication extends StandaloneApplication {
    private $debugEnabled = false;
    private $lookups = array();
    private $authentication = null;

    public function setAuthenticationObject($authentication){
        $this->authentication = $authentication;
    }

    public function addLookup($resourceName, $className = null){
        if (!is_string($className)) {
            $className = $resourceName;
            $resourceName = null;
        }
        if (!is_string($resourceName)) {
            $refl = new \ReflectionClass($className);
            $this->lookups[$refl->getShortName()] = $className;
        }
        if (is_string($resourceName)) {
            $this->lookups[$resourceName] = $className;
        }

        return $this;
    }

    public function addLookups($resources)
    {
        foreach ($resources as $resourceName => $className) {
            if (is_numeric($resourceName)) {
                $resourceName = null;
            }
            $this->addLookup($resourceName, $className);
        }
    }

    public function run()
    {
        try {
            $request = Request::createFromGlobals();
            $path    = explode('/', trim($request->getPathInfo(), '/'));

            // Check authenticate
            $this->authentication->check(trim($request->getPathInfo(), '/'));

            $request->attributes->set('resource', trim($request->getPathInfo(), '/'));
            $response = new Response();
            $response->headers->set('Content-Type', 'application/json');

            switch($path[0]){
                case 'Lookups':
                    $results = array();
                    foreach($this->lookups as $lookup => $className){
                        $results[$lookup] = $this->getQueryResults($className, array());
                    }

                    $response->setContent($this->getSerializer()->serialize($results, 'json'));

                    // $request->query->all()

                    break;
                case 'Authenticate':
                case 'account':
                    if(isset($path[1]) && $this->authentication){
                        $result = $this->authentication->run($path[1], $request);
                        $response->setContent($this->getSerializer()->serialize($result, 'json'));
                    }else{
                        throw new ResourceNotFoundException('No resource found for "' . $request->getPathInfo() . '"');
                    }


                    break;

                default:
                    $response = $this->handle($request);
            }

            $response->send();

        } catch (\Exception $e) {
            if ($this->debugEnabled) {
                throw $e;
            } else {
                $this->sendError($e->getMessage(), $e->getCode());
            }
        }
    }

    protected function sendError($error, $code = 400){
        $response = new Response(json_encode(array(
            'error' => $error,
        )), $code ? $code : 400);
        $response->headers->set('Content-Type', 'application/json');
        $response->send();
    }
}

if( !function_exists('apache_request_headers') ) {
///
    function apache_request_headers() {
        $arh = array();
        $rx_http = '/\AHTTP_/';
        foreach($_SERVER as $key => $val) {
            if( preg_match($rx_http, $key) ) {
                $arh_key = preg_replace($rx_http, '', $key);
                $rx_matches = array();
                // do some nasty string manipulations to restore the original letter case
                // this should work in most cases
                $rx_matches = explode('_', $arh_key);
                if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
                    foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
                    $arh_key = implode('-', $rx_matches);
                }
                $arh[$arh_key] = $val;
            }
        }
        return( $arh );
    }
///
}