/****************************************************************************
 * Funcion	:	lockrec
 * Descripcion	:	Controla el bloqueo de registros
 *                      Se cambio el control que se llevaba en archivos planos 
 *                      a Tabla de base de datos. contbloq.
 * Fecha	:	2003/05/14
 *************************************/
#include <gtk/gtk.h>
#include <stdio.h>
#include "../../def/struct.h"
//#include "../../def/PGgeneral.h"
#include "PGstruct.h"
#include "../../def/general.h"

//extern int inAplicacion_ID;
extern PGconn *conn;
Query ConConsulta();

int lockrec( inTabla )
int inTabla;
{
int inOID;
int inTuplas;
char sbSQL[2000];
char sbUser[21];
int  inEstado;
int  inReturn;
int inAplicacion_ID;
Query stConsulta;
PGresult *resB;
   
   stConsulta = ConConsulta(inTabla, 0);
   if (!stConsulta.inNumIns)
   {
	inError(1, 22, "Error LockRec[0A]: No está current"); 
        return -1;
   }

   if (PQgetvalue(stConsulta.res, 0, 0)==NULL)
   {
	inError(1, 22, "Error LockRec[0B]: No está current"); 
        return -1;
   }
	
   inOID = atoi(PQgetvalue(stConsulta.res, 0,0));
   if (inOID == 0) 
   {
	inError(1, 22, "Error LockRec[0C]: No está current");
        return(-1);
   }
   inAplicacion_ID = getpid( "SIEMPRE" );
   sprintf( sbUser, "%s", getenv( "UUID" ) );
   
   // Consultamos si esta o no Bloqueado
// LOCK TABLE contbloq IN ACCESS EXCLUSIVE MODE;
   sprintf( sbSQL, "BEGIN; \
	    SELECT tabla, rec_oid, usuario, app_id FROM contbloq WHERE rec_oid = %d", inOID);
   resB = PQexec( conn, sbSQL );
   inTuplas = PQntuples( resB );
   if( inTuplas > 0 )  // El registro esta bloqueado
   {
   int inApp_ID;
       inApp_ID = (int)atoi( PQgetvalue( resB, 0, 3 ) );
       if( inAplicacion_ID == inApp_ID )  // Si esta bloqueado y es el mismo
       {
           inReturn = OK;
       }else                              // Es otro usuario y proceso 
       {
           inReturn = FALLO;
       } 
       PQclear( resB );                    // 2004-01-06
       sprintf( sbSQL, "COMMIT;" ); 
       resB = PQexec( conn, sbSQL );
   }else   // El registro no esta bloqueado
   {
       PQclear( resB );
//		 LOCK TABLE contbloq IN SHARE ROW EXCLUSIVE MODE;
       sprintf( sbSQL,"SELECT user_write_lock_oid(oid) FROM %s WHERE oid = %d",
		                                  PGGetNomTab(inTabla), inOID);
       resB = PQexec( conn, sbSQL );  // Lo tratamos de bloquear
       
       if( !PQntuples( resB ) )  // 2003/07/08  
            inEstado = 0;        // Es obvio que NO se pudo bloquear
       else
            inEstado = (int)atoi(PQgetvalue( resB, 0, 0 ) );
	    
       PQclear( resB );
       if( inEstado <= 0 )   // No se pudo bloquear
       {
           sprintf( sbSQL, "ROLLBACK;" ); 
           resB = PQexec( conn, sbSQL );
           inReturn = FALLO;
       }else                 // El bloqueo fue satisfactorio
       {
           sprintf( sbSQL, "INSERT INTO contbloq ( tabla, rec_oid, usuario, app_id ) VALUES ( %d, %d, '%s', %d )", inTabla, inOID, sbUser, inAplicacion_ID );
           resB=PQexec(conn,sbSQL);//Insertamos el registro en la tabla control
           if( PQoidValue( resB ) != InvalidOid )  //
           {
               PQclear( resB );   
               sprintf( sbSQL, "COMMIT" );// todo el trabajo tuvo exito 
               resB = PQexec( conn, sbSQL );
               inReturn = OK;
           }else  // Fallo al crear el registro de control de bloqueo.
           {
               PQclear( resB );   
               sprintf( sbSQL, " SELECT user_write_unlock_oid(oid) FROM %s WHERE oid = %d ; ROLLBACK ", PGGetNomTab(inTabla), inOID);
               resB = PQexec( conn, sbSQL );
               inReturn = FALLO;
           }               
       }
   }
   PQclear( resB );
   return inReturn;
}
