#include <iostream>
#include <sqlite3.h>
//sudo apt install libsqlite3-dev
// g++ filename.cpp -l sqlite3 -o executable.out
// ./executable.out
using namespace std;

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;
	//file:///N:/database/file.sqlite?mode=ro
	exit = sqlite3_open("barcodes.sqlite3", &db);
	if(exit != SQLITE_OK)
	{
		cout << "DB not working\n";
	}
	//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)
	{
		
		std::string barcode_cin = "test";
		while (barcode_cin != "quit" && barcode_cin != "QUIT")
		{
			cout << "\nType quit or Enter 1 barcode (ex.999999):";
			cin >> barcode_cin;
			if (barcode_cin == "quit" || barcode_cin=="QUIT")
			{
				break;
			}
			sqlite3_bind_text(sqlHandler, 1 ,
				barcode_cin.c_str(),
				-1, SQLITE_STATIC);
			int step = sqlite3_step(sqlHandler);
			if(step != SQLITE_ROW)
			{
				cout << barcode_cin << " Not Found\n";
				//another one, reset, bind, step repeat
				sqlite3_reset(sqlHandler);
			}
				
			while(step == SQLITE_ROW)
			{
				//std::string / const unsigned char not same
				//std::string(reinterpret_cast<const char*>(
				// barcodes(barcode text,
				//fullpath text,
				//barcode_type text,
				//pagenum integer,
				//modifytime timestamp
				//re interpret cast
				const unsigned char * row_barcode = 
					sqlite3_column_text(sqlHandler,0);
				const unsigned char* row_path = 
					sqlite3_column_text(sqlHandler,1);
				int row_pagenum = 
					sqlite3_column_int(sqlHandler,3);
				const unsigned char * row_date = 
					sqlite3_column_text(sqlHandler,4);

				printf("Barcode %s path: %s | page:%d\n ",
					row_barcode, row_path,
					row_pagenum 
				);
				step = sqlite3_step(sqlHandler);
				
			}
			//another one, reset, bind, step repeat
			sqlite3_reset(sqlHandler);
		}
	}
	sqlite3_finalize(sqlHandler);

	sqlite3_close(db);
	return (0); 
}

