<?php

include_once ('Ssh2_crontab_manager.php');

/**
 * pruebas actions.
 *
 * @package    canon
 * @subpackage pruebas
 * @author     Harold 
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class cronActions extends sfQuery {

    //-------------
    //CONECTION
    //-------------
//TODO cambiar usuario
//    private $host = '192.168.2.47';
//    private $port = '22';
//    private $user = 'harold';
//    private $password = 'Sistemas';

    public function executeList(sfWebRequest $request) {


        $this->logMessage("---BEGIN Logging request");
        foreach ($request->getPostParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("--------------------------------------------------*  Ip: " . $_SERVER['REMOTE_ADDR']);
        foreach ($request->getGetParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("---END Logging request");
        /*
         * Paginacion
         */
        if (isset($request['_startRow'])) {
            $rowStart = $request['_startRow'];
        } else {
            $rowStart = 0;
        }

        if (isset($request['_endRow'])) {
            $rowEnd = $request['_endRow'];
        } else {
            $rowEnd = 75;
        }
        try {


            $sql = <<<EOD
select count(*) as count from(

   SELECT * FROM cron_manager ORDER BY id_cron_manager
   
)tabla
EOD;

            $total_record_count = CN_TABLE::executeSQL($sql);
            $total_record_count = $total_record_count[0]["count"];

            //validar si hay registros
            if ($total_record_count > 0) {

                /*
                 * Obtiene los accesos para un perfil
                 */
                $sql = <<<EOD
SELECT * FROM ( SELECT row_.*, ROWNUM rownum_ FROM (
            
   SELECT * FROM cron_manager ORDER BY id_cron_manager  
            
) row_ WHERE ROWNUM <=  $rowEnd   ) where rownum_ >  $rowStart
EOD;

                //ejecuta y obtiene el resultado del sql
                $records = CN_TABLE::executeSQL($sql);

                // Solo registra log la primera vez de consulta
                if ($rowStart == 0) {
                    //Operaciones: 1-CONSULTAR, 2-ACTUALIZAR, 3-ADICIONAR, 4-ELIMINAR, 5-ANULAR
                    $id_ope_bd = 1;
                    //obtener id maestro tabla
                    $id_mae_bd = CN_TABLE::consultarIdTablaBD('cron_manager');
                    //registro de consulta en tabla de log- la observacion puede o no enviarse ($request, $id_ope_bd, $id_mae_bd, $observacion)
                    $sql = CN_TABLE::registrarLog($request, $id_ope_bd, $id_mae_bd);
                }

                $this->totalRows = $total_record_count;
                $this->startRow = $rowStart;
                $this->endRow = $rowEnd;
                $this->list_data = $records;
                $this->status = 0;
                $this->logMessage("[CRON LIST] List schedule exitoso!!!");
            } else {

                $mensaje = "[CRON LIST] No hay registros de consulta.";
                $this->status = 1;
                //   $this->mensajeError = $mensaje;
                $this->list_data = array();
                $this->logMessage($mensaje);
            }
        } catch (Exception $e) {
            $records = array();
            $this->list_data = $records;
            $this->logMessage("[CRON LIST] List schedule fallido!!!");
            $this->status = 1;
        }
    }

    public function executeAdd(sfWebRequest $request) {

        $this->logMessage("---BEGIN Logging request");
        foreach ($request->getPostParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("--------------------------------------------------*  Ip: " . $_SERVER['REMOTE_ADDR']);
        foreach ($request->getGetParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("---END Logging request");


        $rowStart = 0;
        $rowEnd = 1;
        //------------
        //DIRECTORY
        //------------
        //Root del proyecto
        $proyectRoot = sfConfig::get("sf_root_dir");

        //Root scripts
        $scriptRoot = $proyectRoot . "/scripts";

        //Scripts
        $scriptDir = $proyectRoot . "/scripts/scripts/";


        //Archivo Scriptella
        $scriptTellaJar = $scriptRoot . "/scriptella.jar";

        //Root logs
        $scriptLogDir = $scriptRoot . "/log/";

        try {

            $func = $request['script_name'];
            $func = $scriptDir . $func;

            
            $minutos = $request['minutes'] . ' ';
            $horas = $request['hours'] . ' ';
            $dias = $request['days'] . ' ';
            $meses = $request['months'] . ' ';
            $dia_semana = $request['day_of_week'] . ' ';
            $nameSchedule = $request['nombre'] . ' ';
            $date = chr(96)."date".chr(96);
            $nameScheduleTrim = $date.str_replace(" ", "", $nameSchedule);
            $log = $scriptLogDir . $nameScheduleTrim . '.log ';

            //------------    
            //PARAMETERS
            //-------------

            $comando = $minutos . $horas . $dias . $meses . $dia_semana;
            $comando.='java -jar ' . $scriptTellaJar . " ";
            $comando.=$func . ' ';
            $comando.='>> ' . $log . ' 2>&1';

            //----------------
            //EXECUTE CRON 
            //----------------

            $crontab = new Ssh2_crontab_manager(sfConfig::get("app_host"), sfConfig::get("app_port"), sfConfig::get("app_user"), sfConfig::get("app_password"));
            $crontab->append_cronjob($comando);

            $sql = <<<EOD

INSERT INTO CRON_MANAGER VALUES( '' , '$nameSchedule','$func', '$minutos', '$horas', '$dias', '$meses', '$dia_semana', '/log/$nameScheduleTrim.log')  
   
EOD;
            CN_TABLE::executeSQL($sql);

            $sql = <<<EOD
SELECT * FROM ( SELECT row_.*, ROWNUM rownum_ FROM (
            
select * from CRON_MANAGER  order by ID_CRON_MANAGER desc 
            
) row_ WHERE ROWNUM <=  $rowEnd   ) where rownum_ >  $rowStart
EOD;

            //ejecuta y obtiene el resultado del sql
            $records = CN_TABLE::executeSQL($sql);

            //Operaciones: 1-CONSULTAR, 2-ACTUALIZAR, 3-ADICIONAR, 4-ELIMINAR, 5-ANULAR
            $id_ope_bd = 3;
            //obtener id maestro tabla
            $id_mae_bd = CN_TABLE::consultarIdTablaBD('cron_manager');
            //registro de consulta en tabla de log- la observacion puede o no enviarse ($request, $id_ope_bd, $id_mae_bd, $observacion)
            $sql = CN_TABLE::registrarLog($request, $id_ope_bd, $id_mae_bd, "Se adiciona una tarea al CRON manager");

            $this->totalRows = 1;
            $this->startRow = $rowStart;
            $this->endRow = $rowEnd;
            $this->list_data = $records;
            $this->status = 0;
            $this->logMessage("[CRON ADD] Add schedule exitoso!!!");
        } catch (Exception $e) {

            $records = array();
            $this->list_data = $records;
            $this->logMessage("[CRON ADD] Acición schedule fallido!!!");
            $this->status = 1;
        }
    }

    public function executeRemove(sfWebRequest $request) {

        $this->logMessage("---BEGIN Logging request");
        foreach ($request->getPostParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("--------------------------------------------------*  Ip: " . $_SERVER['REMOTE_ADDR']);
        foreach ($request->getGetParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("---END Logging request");

        $id_cron = $request['id_cron_manager'];

        try {

            $sql = <<<EOD

  DELETE FROM CRON_MANAGER WHERE id_cron_manager=$id_cron
   
EOD;
            CN_TABLE::executeSQL($sql);

            //Resincroniza con base de datos los procesos existentes
            $this->deleteAddCron($request);

            $temp = array();
            $temp["id_cron_manager"] = $id_cron;
            $records = array();
            $records[] = $temp;

            //Operaciones: 1-CONSULTAR, 2-ACTUALIZAR, 3-ADICIONAR, 4-ELIMINAR, 5-ANULAR
            $id_ope_bd = 4;
            //obtener id maestro tabla
            $id_mae_bd = CN_TABLE::consultarIdTablaBD('cron_manager');
            //registro de consulta en tabla de log- la observacion puede o no enviarse ($request, $id_ope_bd, $id_mae_bd, $observacion)
            $sql = CN_TABLE::registrarLog($request, $id_ope_bd, $id_mae_bd, "Se elimina una tarea del CRON manager");


            $this->list_data = $records;
            $this->status = 0;
            $this->logMessage("[CRON DELETE] Delete schedule exitoso!!!");
        } catch (Exception $e) {
            $records = array();
            $this->list_data = $records;
            $this->logMessage("[CRON DELETE] Delete schedule fallido!!!");
            $this->status = 1;
        }
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->logMessage("---BEGIN Logging request");
        foreach ($request->getPostParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("--------------------------------------------------*  Ip: " . $_SERVER['REMOTE_ADDR']);
        foreach ($request->getGetParameters() as $key => $value) {
            $this->logMessage("request[$key] = $value");
        }
        $this->logMessage("---END Logging request");

        try {

            $func = $request['script_name'];
            $minutos = $request['minutes'];
            $horas = $request['hours'];
            $dias = $request['days'];
            $meses = $request['months'];
            $dia_semana = $request['day_of_week'];
            $nameSchedule = $request['nombre'];
	    $date = chr(96)."date".chr(96);
            $nameScheduleTrim = $date.str_replace(" ", "", $nameSchedule);
            $id_cron = $request['id_cron_manager'];

            $sql = <<<EOD

UPDATE CRON_MANAGER 
SET  NOMBRE='$nameSchedule', MINUTES='$minutos', HOURS='$horas', MONTHS='$meses', DAYS='$dias', DAY_OF_WEEK='$dia_semana', SCRIPT_NAME='$func', LOG_NAME='/log/$nameScheduleTrim.log'
WHERE ID_CRON_MANAGER=$id_cron 
   
EOD;
            $records = CN_TABLE::executeSQL($sql);

            $this->deleteAddCron($request);

            //Operaciones: 1-CONSULTAR, 2-ACTUALIZAR, 3-ADICIONAR, 4-ELIMINAR, 5-ANULAR
            $id_ope_bd = 2;
            //obtener id maestro tabla
            $id_mae_bd = CN_TABLE::consultarIdTablaBD('cron_manager');
            //registro de consulta en tabla de log- la observacion puede o no enviarse ($request, $id_ope_bd, $id_mae_bd, $observacion)
            $sql = CN_TABLE::registrarLog($request, $id_ope_bd, $id_mae_bd);



            $this->list_data = $records;
            $this->status = 0;
            $this->logMessage("[CRON UPDATE] Update schedule exitoso!!!");
        } catch (Exception $e) {
            $records = array();
            $this->list_data = $records;
            $this->logMessage("[CRON UPDATE] Update schedule fallido!!!: $e");
            $this->status = 1;
        }
    }

    /**
     * Resincroniza los procesos con la informacion de la BD
     * @param sfWebRequest $request
     */
    private function deleteAddCron(sfWebRequest $request) {

        //Eliminar registros en el cron 

        $crontab = new Ssh2_crontab_manager(sfConfig::get("app_host"), sfConfig::get("app_port"), sfConfig::get("app_user"), sfConfig::get("app_password"));
        $crontab->remove_crontab();

        //Adicionar nuevamente las tareas
        //------------
        //DIRECTORY
        //------------
        //Root del proyecto
        $proyectRoot = sfConfig::get("sf_root_dir");

        //Root scripts
        $scriptRoot = $proyectRoot . "/scripts";

        //Scripts
        $scriptDir = $proyectRoot . "/scripts/scripts/";

        //Archivo Scriptella
        $scriptTellaJar = $scriptRoot . "/scriptella.jar";

        //Root logs
        $scriptLogDir = $scriptRoot . "/log/";

        $sql = <<<EOD

   SELECT * FROM cron_manager ORDER BY id_cron_manager
 
EOD;

        $records = CN_TABLE::executeSQL($sql);

        foreach ($records as $value) {

            $minutos = $value['minutes'] . ' ';
            $horas = $value['hours'] . ' ';
            $dias = $value['days'] . ' ';
            $meses = $value['months'] . ' ';
            $dia_semana = $value['day_of_week'] . ' ';
            $nameSchedule = $request['nombre'] . ' ';
	    $date = chr(96)."date".chr(96);
            $nameScheduleTrim = $date.str_replace(" ", "", $nameSchedule);
            $log = $scriptLogDir . $nameScheduleTrim . '.log ';
            $func = $value['script_name'];

            //------------    
            //PARAMETERS
            //-------------

            $comando = $minutos . $horas . $dias . $meses . $dia_semana;
            $comando.='java -jar ' . $scriptTellaJar . " ";
            $comando.=$func . ' ';
            $comando.='>> ' . $log . ' 2>&1';

            //----------------
            //EXECUTE CRON 
            //----------------

            $crontab = new Ssh2_crontab_manager(sfConfig::get("app_host"), sfConfig::get("app_port"), sfConfig::get("app_user"), sfConfig::get("app_password"));
            $crontab->append_cronjob($comando);
        }
    }

    // Validate
    /**
     * Ejecuta una validación previa a la ejecución de una operación tipo Add
     *
     * @param sfWebRequest $request
     * @return array 
     */
    protected function validateAdd(sfWebRequest $request) {

        //valor por defecto
        $errors = null;

        /*
         *  Validar la operación, ya sea por SQL
         */

        /*
         *  Generar errores en $errors
         */

        return $errors;
    }

    /**
     * Ejecuta una validación previa a la ejecución de una operación tipo Update
     *
     * @param sfWebRequest $request
     * @return array 
     */
    protected function validateUpdate(sfWebRequest $request) {

        //valor por defecto
        $errors = null;

        /*
         *  Validar la operación, ya sea por SQL
         */

        /*
         *  Generar errores en $errors
         */

        return $errors;
    }

    /**
     * Ejecuta una validación previa a la ejecución de una operación tipo Remove
     *
     * @param sfWebRequest $request
     * @return array 
     */
    protected function validateRemove(sfWebRequest $request) {

        //valor por defecto
        $errors = null;

        /*
         *  Validar la operación, ya sea por SQL
         */

        /*
         *  Generar errores en $errors
         */

        return $errors;
    }

    /**
     * Acciones anteriores a la original
     * 
     * return sfWebRequest Changed Request with additional parameters.
     * 
     * @param type $Action ( ADD, UPDATE, REMOVE )
     * @param sfWebRequest $request
     * @return \sfWebRequest 
     */
    protected function preprocessRequest($Action, sfWebRequest $request) {

        /*
         * Se instancia la clase del manejo del log
         */
        $logger = sfContext::getInstance()->getLogger();
        $logger->info("Entro a preprocessRequest");

        /*
         * Procesar Request
         */
        //accion add
        if ($Action == "ADD") {
            
        }

        //accion update
        if ($Action == "UPDATE") {
            
        }

        //accion remove
        if ($Action == "REMOVE") {
            
        }

        return $request;
    }

    /**
     * Acciones posteriores a la original
     * 
     * return sfWebRequest Changed Request with additional parameters.
     * 
     * @param type $Action ( ADD, UPDATE, REMOVE )
     * @param sfWebRequest $request
     * @return \sfWebRequest 
     */
    protected function postprocessRequest($Action, sfWebRequest $request, $list_data_post) {

        /*
         * Se instancia la clase del manejo del log
         */
        $logger = sfContext::getInstance()->getLogger();
        $logger->info("Entro a postprocessRequest - " . $list_data_post);

        /*
         * Procesar Request
         */
        //accion add
        if ($Action == "ADD") {
            
        }

        //accion update
        if ($Action == "UPDATE") {
            
        }

        //accion remove
        if ($Action == "REMOVE") {
            
        }

        return $request;
    }

}
