<?php

class userReindexTask extends sfBaseTask
{
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
    ));

    $this->namespace        = 'user';
    $this->name             = 'reindex';
    $this->briefDescription = 'rebuld index for users search';
    $this->detailedDescription = <<<EOF
The [rebuild|INFO] task rebuilds index from users data
Call it with:
  [php symfony user:reindex|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    $index = UserTable::getLuceneIndex();

    // count nb users
    $q = Doctrine_Query::create()
      ->Select('count(*) as num_users')
      ->from('user u');
    $count = $q->fetchArray();
    $nbUsers = $count[0]['num_users'];
    $this->logSection('recreateIndex', 'rebuild index for' . $nbUsers . ' users');


    // rebuild index by part of $part
    $part = 500;
    for($limit=0; $limit <= $nbUsers; $limit += $part) {
      // select all users
      $q = Doctrine_Query::create()
        ->from('user u')
        ->where('id >= ?',$limit)
        ->andWhere('id <= ?', $limit + $part);
    
      $this->logSection('recreateIndex', 'building user ids from ' . $limit . ' to ' . ($limit + $part));
      // recreate Lucene index entries
      $users = $q->execute();
      foreach ($users as $user)
      {
        // remove existing entries
        foreach ($index->find('pk:'.$user->getId()) as $hit)
        {
          $index->delete($hit->id);
        }
   
        $doc = new Zend_Search_Lucene_Document();
 
        // store job primary key to identify it in the search results
        $doc->addField(Zend_Search_Lucene_Field::Keyword('pk', $user->getId())); 
 
        // index job fields
        $doc->addField(Zend_Search_Lucene_Field::UnStored('login', $user->getLogin(), 'utf-8'));
        $doc->addField(Zend_Search_Lucene_Field::UnStored('email', $user->getEmail(), 'utf-8'));
        $doc->addField(Zend_Search_Lucene_Field::UnStored('firstname', $user->getFirstname(), 'utf-8'));
        $doc->addField(Zend_Search_Lucene_Field::UnStored('lastname', $user->getLastname(), 'utf-8'));
 
        // add job to the index
        $index->addDocument($doc);
        $index->commit();
      }
      
      unset($user);
      $index->optimize();
    }
    $this->logSection('lucene', 'Cleaned up and optimized the user index');
  }
}
