<?php
require_once APPLICATION_PATH . '/Acl.php';

/**
 * Bootstrap this shit
 */
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    /**
     * Setup navigaion
     *
     * @return Zend_Navigation $navigation
     */
    protected function _initNav()
    {
        $this->bootstrap('translate');
        $this->bootstrap('view');
        $this->bootstrap('acl');
        $this->bootstrap('models');
        

        $navConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml', 'navigation');
        $navigation = new Zend_Navigation($navConfig);
        
        $view = $this->getResource('view');
        $view->navigation()->setTranslator($this->getResource('translate'));
        $view->navigation($navigation);
        $view->navigation()->setAcl($this->getResource('acl'));

        // Set userrole for navigation
        $auth = Zend_Auth::getInstance();
        
        if ($auth->hasIdentity()) {
            $view->navigation()->setRole($auth->getIdentity()->userRole);
        } else {
            $view->navigation()->setRole(Acl::ROLE_VISITOR);
        }
  
        return $navigation;
    }

    /**
     * Setup layout
     *
     * @return Zend_Layout $layout
     */
    protected function _initLayout()
    {
        $layout = Zend_Layout::startMvc();

        return $layout;
    }


    /**
     * View and Layout configuration
     *
     * @return Zend_View $view
     */
    protected function _initView()
    {
        $this->bootstrap('layout');

        $view = $this->getResource('layout')->getView();
        
        $view->doctype('XHTML1_STRICT');
        $view->setEncoding('UTF-8');
        $view->headMeta()->appendHttpEquiv('Content-Type','text/html;charset=utf-8');

        // Set site title from application.ini
        $config = $this->getApplication()->getOptions();
        $view->headTitle($config['app']['name']);

        // Set helper path
        $view->addHelperPath('Fiktiv/View/Helper/', 'Fiktiv_View_Helper');

        $view->app = $this->getApplication()->getOption('app');

        // Add jQuery :)
        $view->headScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
        
        Zend_Locale::setDefault('sv_SE');

        return $view;
    }

    /**
     * Configure the front controller
     *
     * @return Zend_Controller_Front $frontController
     */
    protected function _initFront()
    {
        $this->bootstrap('autoloader');

        // Get front controller
        $frontController = Zend_Controller_Front::getInstance();
        
        // Set modules directory 
        $frontController->addModuleDirectory(APPLICATION_PATH . '/modules');

        // Add plugins
        $frontController->registerPlugin(new Fiktiv_Controller_Plugin_Language());
        $frontController->registerPlugin(new Fiktiv_Controller_Plugin_Navigation());
        $frontController->registerPlugin(new Fiktiv_Controller_Plugin_Layout());

        return $frontController;
    }

    /**
     * Configure routes for our application
     *
     * @return Zend_Controller_Router_Rewrite $router
     */
    protected function _initRouter()
    {
        // Make sure the front controller is ready
        $this->bootstrap('front');

        $router = $this->getResource('front')->getRouter();

        // Use request params
        //$router->useRequestParametersAsGlobal(false);
        
        // Set global lang param
        $router->setGlobalParam('lang', 'sv');

        // Default route to default module
        $router->addRoute('default', new Zend_Controller_Router_Route(':lang/:controller/:action/*',
        array(
            'module' => 'default',
            'controller' => 'index',
            'action' => 'index'
        )));

        // Allow "direct access" to index controller in default module
        $router->addRoute('default-default', new Zend_Controller_Router_Route(':lang/:action/*',
        array(
            'module' => 'default',
            'controller' => 'index',
            'action'    => 'index'
        ),
        array(
            'action' => '(about)'
        )));


        // Routes for blog module
        $router->addRoute('blog',new Zend_Controller_Router_Route(':lang/blog/:controller/:action/*',array(
            'module'        => 'blog',
            'controller'    => 'index',
            'action'        => 'index',
        )));
        $router->addRoute('blog-default',new Zend_Controller_Router_Route(':lang/blog/:action/:id',array(
            'module'        => 'blog',
            'controller'    => 'index',
            'action'        => 'latest',
            'id'            => ''
        ),array(
            'action'        => '(latest|read|readable)'
        )));


        // Route for admin?
        $router->addRoute('admin', new Zend_Controller_Router_Route(':lang/admin/:controller/:action/*',array(
            'module' => 'admin',
            'controller' => 'index',
            'action' => 'index'
        )));


        // Route for auth
        $router->addRoute('auth', new Zend_Controller_Router_Route(':lang/:action',array(
            'module' => 'default',
            'controller' => 'auth',
        ),array(
            'action' => '(login|logout)'
        )));
        
        return $router;
    }

    /**
     * Configure global and local(modules) models
     */
    protected function _initModels()
    {
        $this->bootstrap('front');
        $this->bootstrap('autoloader');

        // Include global model directory
        set_include_path(implode(PATH_SEPARATOR, array(
            APPLICATION_PATH . '/models',
            APPLICATION_PATH . '/models/rows',
            get_include_path()
        )));

        // Let our model autoloader plugin handle local models
        $front = $this->getResource('front');
        $front->registerPlugin(new Fiktiv_Controller_Plugin_ModelAutoloader());

    }

    /**
     * Configure autoloader
     *
     * @return Zend_Loader_Autoloader $autoloader
     */
    protected function _initAutoloader()
    {
        $this->bootstrap('session');

        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('Fiktiv_');
        $autoloader->setFallbackAutoloader(true);

        return $autoloader;
    }

    /**
     * Configure multilanguage (translator)
     *
     * @return Zend_Translate $translate
     */
    protected function _initTranslate()
    {
        $this->bootstrap('autoloader');

        $translate = new Fiktiv_Translate(array(
            'adapter' => 'Fiktiv_Translate_Adapter_Ini',
            'locale' => 'sv',
            'content' => APPLICATION_PATH . '/languages/se.ini'
        ));

        $translate->addTranslation(APPLICATION_PATH . '/languages/en.ini', 'en');

        Zend_Form::setDefaultTranslator($translate);

        Zend_Registry::set('Zend_Translate', $translate);

        return $translate;
    }

    /**
     * Setup a sweet and simple database
     * connection.
     *
     * @return Zend_Db
     */
    protected function _initDatabase()
    {
        // Access config for database user/pass ..
        $config = $this->getApplication()->getOptions();

        // Setup database adapter
        $database = Zend_Db::factory($config['db']['adapter'], $config['db']);

        // Use the  adapter by default
        Zend_Db_Table::setDefaultAdapter($database);

        return $database;
    }

    /**
     * Setup auth
     *
     * @return Zend_Auth
     */
    protected function _initAuth()
    {
        $this->bootstrap('session');

        $auth = Zend_Auth::getInstance();

        return $auth;
    }

    /**
     * Setup session
     *
     * @return Zend_Session $session
     */
    protected function _initSession()
    {
        $this->bootstrap('database');

        // Setup session storage in database
        $options = array(
            'name'              => 'Session',
            'primary'           => 'sid',
            'modifiedColumn'    => 'mtime',
            'lifetimeColumn'    => 'ltime',
            'dataColumn'        => 'data'
        );

        $handler = new Zend_Session_SaveHandler_DbTable($options);

        Zend_Session::setSaveHandler($handler);

        // Now, start session.
        Zend_Session::start();

        // TODO: Better name for global session namespace (default namespace)
        $defaultNamespace = new Zend_Session_Namespace('global');

        return $defaultNamespace;
    }

    /**
     * Load accessrights
     */
    protected function _initAcl()
    {
        $acl = new Acl();

        Zend_Registry::set('Zend_Acl', $acl);

        return $acl;
    }


    /**
     * This is just a temporary.
     * 
     */
    protected function _initOther()
    {
        // Add action helpers. Maybe should this should be in the frontController setup?
        Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/../library/Fiktiv/Controller/Action/Helper',
                                                                                                'Fiktiv_Controller_Action_Helper');
    }
}
