#include "common_tool.h"
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
//#include "interswitch_sendmoney.h"
#include "safestring.h"
#include "cfg.h"
#include <string>
#include "pgsql_wrapper.h"
#include "pgsql.h"

//char confirmation[20] = "";
//Confirmation(payment_id, confirmation, sizeof (confirmation));
void GenerateConfirmationSeed( char * number, int sz, int seed );

void GenerateConfirmation( char * number, int sz )
{
	GenerateConfirmationSeed(number,sz,1);
}

void GenerateConfirmationSeed( char * number, int sz, int seed )
{
        char chars[] = "WRB01234WRB56789WRBXQFDTYP";
        int n = sizeof(chars);
        int i;
/*
        time_t t;
        time( &t );
        pid_t pid = getpid();

        srand(t+pid);
*/
	srand((unsigned int)time((time_t *)NULL));

        for ( i=0; i<10 && i<sz-1; i++ )
        {
		int k = seed%n;
		if (seed>1 && k==i) {
			number[i] = chars[n-k];
		} else {
                	number[i] = chars[ (int) ( (n-1.0)*rand()/(RAND_MAX+1.0)) ];
		}
        }
        number[i] = 0;
}

void RandomAlphaNumeric( char * number, int sz, int seed )
{
        char chars[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int n = sizeof(chars);
        int i;
/*
        time_t t;
        time( &t );
        pid_t pid = getpid();

        srand(t+pid);
*/
	srand((unsigned int)time((time_t *)NULL));

        for ( i=0; i<10 && i<sz-1; i++ )
        {
		int k = seed%n;
		if (seed>1 && k==i) {
			number[i] = chars[n-k];
		} else {
                	number[i] = chars[ (int) ( (n-1.0)*rand()/(RAND_MAX+1.0)) ];
		}
        }
        number[i] = 0;
}



void Confirmation( unsigned long  payment_id, char * number, int sz )
{
	SQLINTEGER rows;
	char confirmation[11];

   // Lock table to prevent generation of two identical confirmation numbers
	pgsql_exec("BEGIN; LOCK TABLE members_payments;" );
	int i = 0;
	do
	{
		GenerateConfirmationSeed( confirmation, sizeof(confirmation), i++ );

        	//st.CloseCursor();
			rows = 0;		
			const PGresult *res = pgsql_query("SELECT id FROM members_payments WHERE confirmation='%s'", confirmation );
			if (res!=NULL )						
			{
			    rows = pgsql_num_rows(res);
			}
	} while ( rows>0 && i<100 );
	
	pgsql_exec("UPDATE members_payments SET confirmation='%s', dt_confirmed=now() WHERE id=%lu", confirmation, payment_id );
	pgsql_exec("COMMIT" );         // Unlock table 'data'
	strsafecpy( number, confirmation, sz );
}


void GetOfferCode( unsigned long  offer_id, char * number, int sz )
{
	SQLINTEGER rows;
	char offer_code[14];

   // Lock table to prevent generation of two identical confirmation numbers
	pgsql_exec("BEGIN; LOCK TABLE members_jobs_offer;" );
	int i = 0;
	do
	{
		GenerateConfirmationSeed( offer_code, sizeof(offer_code), i++ );

        	//st.CloseCursor();
			rows = 0;		
			const PGresult *res = pgsql_query("SELECT id FROM members_jobs_offer WHERE offer_code='%s'", offer_code );
			if (res!=NULL )						
			{
			    rows = pgsql_num_rows(res);
			}
	} while ( rows>0 && i<100 );

	pgsql_exec("UPDATE members_jobs_offer SET offer_code='%s' WHERE id=%lu", offer_code, offer_id );
	pgsql_exec("COMMIT" );         // Unlock table 'data'
	strsafecpy( number, offer_code, sz );
}


void SetFamilyUsername( unsigned long  family_id, char * number, int sz )
{
	SQLINTEGER rows;
	char family_username[7]; // 6 characters + \0
  bzero(family_username, sizeof(family_username));

   // Lock table to prevent generation of two identical username
	pgsql_exec("BEGIN; LOCK TABLE members_family;" );
	int i = 0;
	do
	{
		//GenerateConfirmationSeed( family_username, sizeof(family_username), i++ );
    RandomAlphaNumeric( family_username, sizeof(family_username), i++ );

        	//st.CloseCursor();
			rows = 0;
			const PGresult *res = pgsql_query("SELECT id FROM members_family WHERE username='%s'", family_username );
			if (res!=NULL )
			{
			    rows = pgsql_num_rows(res);
			}
	} while ( rows>0 && i<100 );

	pgsql_exec("UPDATE members_family SET username='%s' WHERE id=%lu", family_username, family_id );
	pgsql_exec("COMMIT" );         // Unlock table 'data'
	strsafecpy( number, family_username, sz );
}
/*
CREATE TABLE members_recentactivities (
		id SERIAL,
		member_id INT REFERENCES members(id) NOT NULL,
		uid  uuid  DEFAULT uuid_generate_v4(),
		title VARCHAR(35) NOT NULL,
		description VARCHAR(100),
		status INT DEFAULT 1,
		added timestamp without time zone DEFAULT now()
	);
 ALTER TABLE ONLY members_recentactivities
    ADD CONSTRAINT members_recentactivities_id_key UNIQUE (id);

    ALTER TABLE members_recentactivities ALTER COLUMN title TYPE  VARCHAR(60);
*/
long WrenchLogRecent(CVars in, CVars &out) {
    long ret = PHP_API_BAD_PARAM;
    logfmt(logINFO, "WrenchLogRecent()");
    try {
        REQ_LONG(in, "member_id", 1, -1);
        REQ_STRING(in, "title", 5, 60, "(.*)");
        REQ_STRING(in, "description", 5, 100, "(.*)");

        CVars xx;
		xx["member_id"] = in["member_id"]; xx["member_id"].set_valid(true);
		xx["title"]    = in["title"];    xx["title"].set_valid(true);
		xx["description"] = in["description"]; xx["description"].set_valid(true);
		out["recent_id"] = insert_db_record(DBS_VALID, "members_recentactivities", "members_recentactivities_id_seq", xx);

    }    catch (bad_parameter) {
        out["log_status"] = "Something went wrong";
    }
    logfmt(logINFO, "WrenchLogRecent()");
    return ret;
}


