<?php

class SearchController extends Controller {

    /**
     * @var string index dir as alias path from <b>application.</b>  , default to <b>runtime.search</b>
     */
    private $_indexFiles = 'runtime.search';

    /**
     * (non-PHPdoc)
     * @see CController::init()
     */
    public function init() {
        Yii::import('application.vendors.*');
        require_once('Zend/Search/Lucene.php');
        parent::init();
    }

    public function actionCreate() {
        $index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.' . $this->_indexFiles), true);

        $candidatos = Candidato::model()->findAll();
        foreach ($candidatos as $candidato) {
            $doc = new Zend_Search_Lucene_Document();
            $doc->addField(Zend_Search_Lucene_Field::UnIndexed('id', $candidato->id));
            $doc->addField(Zend_Search_Lucene_Field::Text('nombre', CHtml::encode($candidato->nombre), 'utf-8'));
            $doc->addField(Zend_Search_Lucene_Field::Text('apellidos', CHtml::encode($candidato->apellidos), 'utf-8'));
            $doc->addField(Zend_Search_Lucene_Field::Text('n_identificacion', CHtml::encode($candidato->n_identificacion), 'utf-8'));
            echo "\tAdding: " . $candidato->id . "\n";
            $index->addDocument($doc);
        }
        $index->commit();
        echo 'Lucene index created';
    }

    public function actionSearch() {
        $results = array();
        
        if (($term = Yii::app()->getRequest()->getParam('q', null)) !== null) {
            if (str_word_count($term) == 1) $term .= '*';
            $index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.' . $this->_indexFiles));
            
            try {
                $results = $index->find($term);
                $query = Zend_Search_Lucene_Search_QueryParser::parse($term);
            } catch (Exception $e) {
                if ($e instanceof Zend_Search_Lucene_Exception) {
                    Yii::app()->user->setFlash('error', Yii::t('profind', 'Indique un término de búsqueda de al menos 3 caracteres'));
                }
            }
            
            $pages = new CPagination(count($results));
            $currentPage = Yii::app()->getRequest()->getQuery('page', 1);
            $pages->pageSize = 10;            
            
            $this->render('search', compact('results', 'term', 'query', 'pages', 'currentPage'));
        } else
            throw new CHttpException(400, Yii::t('profind', 'Petición no válida'));
    }

}

?>