#include <iostream>
#include <sqlite3.h>
//sqlite3 needs to be compiled if you don't have ubuntu
//if you have ubuntu use
//sudo apt install libsqlite3-dev 
//INSTALLS sqlite3.h headers without having to compile below
//then run using 
// g++ hello-world-sqlite-3.cpp -l sqlite3 -o hello-world-sqlite3.out
// ./hello-world-sqlite3.out
// if windows see if there is a 32 bit .dll file for mingw
//to compile manually need to get source
//since programming in c, can use amalgamation source file sqlite3.c
//grab shell.c sqlite3.c and sqlite3.h from tarball
//gcc shell.c sqlite3.c -lpthread -ldl
//pthread library  multi thread
//dl dynamic loading
//full -lreadline -lncurses -o sqlite3
//o = output file name
//sudo apt install libreadline-dev libncurses-dev
//in windows g++ -shared sqlite3.c -o sqlite3.dll
using namespace std;
//for c_str()


int main(int argc, char **argv)
{
	sqlite3 *db;
	// 5 steps to do a single prepared statement
	//www.sqlite.org/c3ref/stmt.html
	std::string sqlStatement = "SELECT * FROM barcodes where barcode = ? ORDER BY modifytime DESC;";
	int exit = 0;
	//OEN UTF 8 read write
	//file:///N:/database/file.sqlite?mode=ro
	exit = sqlite3_open("barcodes.sqlite3", &db);
	if(exit != SQLITE_OK) 
	{
		std::cerr << "Error open db" << sqlite3_errmsg(db) << std::endl;
		return (-1);
	}
	else
	{
		std::cout << "SQL Database opened" << std::endl;
	}
	char * messageError;

//Create the prepared statement object using sqlite3_prepare_v2().
//Bind values to parameters using the sqlite3_bind_*() interfaces.
//Run the SQL by calling sqlite3_step() one or more times.
//Reset the prepared statement using sqlite3_reset() then go back to step 2. Do this zero or more times.
//Destroy the object using sqlite3_finalize().
	sqlite3_stmt * sqlHandler;
	//int sqlite3_prepare_v2(
	//sqlite3 *db,            /* Database handle */
	//const char *zSql,       /* SQL statement, UTF-8 encoded */
	//int nByte,              /* Maximum length of zSql in bytes. */
	//sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
	//const char **pzTail     /* OUT: Pointer to unused portion of zSql */
	//If the nByte argument is negative, then zSql is read up to the first zero terminator.
	exit = sqlite3_prepare_v2(db, sqlStatement.c_str(), 
		-1, &sqlHandler, 0);
	
	if (exit == SQLITE_OK)
	{
		sqlite3_bind_text(sqlHandler, 1 , "999999",
			-1, SQLITE_STATIC);
		int step = sqlite3_step(sqlHandler);
		if(step == SQLITE_ROW)
		{
			printf("Barcode %s path: %s\n",
				sqlite3_column_text(sqlHandler,0),
				sqlite3_column_text(sqlHandler,1)
			);
		
		}
		//another one
		sqlite3_reset(sqlHandler);
		sqlite3_bind_text(sqlHandler, 1 , "999999",
			-1, SQLITE_STATIC);
		step = sqlite3_step(sqlHandler);
		if(step == SQLITE_ROW)
		{
			printf("Barcode %s path: %s\n",
				sqlite3_column_text(sqlHandler,0),
				sqlite3_column_text(sqlHandler,1)
			);
		
		}
		
	}
	sqlite3_finalize(sqlHandler);

	sqlite3_close(db);
	return (0); 
}

