#include "stdafx.h"
#include "testpglib.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libpq-fe.h>
#include <c.h>


void exit_nicely(PGconn *conn)
{
    PQfinish(conn);
		return;
}



int main(int argc, char* argv[])
{
	printf("Hello World!\n");

	/* Test 4 using the postgis  wkb binary data */
	test_4();

	return 0;
}


/*
 * test4.c Test the C version of Libpq, the Postgres frontend
 * library. tests the binary cursor interface
 * 
 * Get the WBK binary back 
 *
 */

void test_4()
{
    char       *pghost,
               *pgport,
               *pgoptions,
               *pgtty;
    char       *dbName,
							 *user,
							 *pass;
    int         i;

    int         i_fnum,
                d_fnum,
                p_fnum;
    PGconn     *conn;
    PGresult   *res;


    pghost = "192.168.1.128";              /* host name of the backend server */
    pgport = "5432";              /* port of the backend server */
    pgoptions = NULL;           /* special options to start up the backend
                                * server */
    pgtty = NULL;               /* debugging tty for the backend server */
    dbName= "test";
		user  = "postgres";
    pass  = "admin";

    /* make a connection to the database */
    conn = PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName, user, pass);
    /*
     * check to see that the backend connection was successfully made
     */
    if (PQstatus(conn) == CONNECTION_BAD)
    {
        fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
        fprintf(stderr, "%s", PQerrorMessage(conn));
        exit_nicely(conn);
    }

    /* start a transaction block */
    res = PQexec(conn, "BEGIN");
    if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    {
        fprintf(stderr, "BEGIN command failed\n");
        PQclear(res);
        exit_nicely(conn);
    }

    /*
     * should PQclear PGresult whenever it is no longer needed to avoid
     * memory leaks
     */
    PQclear(res);

    /*
     * fetch rows from the pg_database, the system catalog of
     * databases
     */
    // res = PQexec(conn, "DECLARE mycursor BINARY CURSOR FOR select i, d, AsBinary(p) from test1");
		// res = PQexec(conn, "DECLARE mycursor BINARY CURSOR FOR select gid, name, asbinary(the_geom) from canada where gid =1");
		res = PQexec(conn, "DECLARE mycursor BINARY CURSOR FOR select gid, name, asbinary(the_geom) from canada where gid =13");
    if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
    {
        fprintf(stderr, "DECLARE CURSOR command failed\n");
        PQclear(res);
        exit_nicely(conn);
    }
    PQclear(res);

    res = PQexec(conn, "FETCH ALL in mycursor");
    if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
    {
        fprintf(stderr, "FETCH ALL command didn't return tuples properly\n");
        PQclear(res);
        exit_nicely(conn);
    }

    i_fnum = PQfnumber(res, "gid");
    d_fnum = PQfnumber(res, "name");
    p_fnum = PQfnumber(res, "asbinary");

    for (i = 0; i < 3; i++)
    {
        printf("type[%d] = %d, size[%d] = %d\n",
               i, PQftype(res, i),
               i, PQfsize(res, i));
    }

    for (i = 0; i < PQntuples(res); i++)
    {
        int        *ival;
        float      *dval;
		    int         plen;
        char	     *pval;
 		    FILE *stream;



        /* we hard-wire this to the 3 fields we know about */
        ival = (int *) PQgetvalue(res, i, i_fnum);
        dval = (float *) PQgetvalue(res, i, d_fnum);
        plen = PQgetlength(res, i, p_fnum);

        /*
         * plen doesn't include the length field so need to
         * increment by VARHDSZ
         */
        pval = (char *) malloc(plen);
        memmove(pval, PQgetvalue(res, i, p_fnum), plen);

			 /* Open file in text mode: */
			 if( (stream = fopen( "fLineString.out", "w+" )) != NULL )
			 {
					int numwritten = fwrite( pval, 1, plen, stream );
					printf( "Wrote %d items\n", numwritten );
					fclose( stream );
			 }
			 else
		      printf( "Problem opening the file\n" );

        printf("tuple %d: got\n", i);
        printf(" i = (%d bytes) %d,\n",
               PQgetlength(res, i, i_fnum), *ival);
        printf(" d = (%f bytes) %f,\n",
               PQgetlength(res, i, d_fnum), *dval);
        printf(" p = (%d bytes) \n",
               PQgetlength(res, i, p_fnum));
				
    }
    PQclear(res);

    /* close the cursor */
    res = PQexec(conn, "CLOSE mycursor");
    PQclear(res);

    /* commit the transaction */
    res = PQexec(conn, "COMMIT");
    PQclear(res);

    /* close the connection to the database and cleanup */
    PQfinish(conn);

    return ;
}



