#include "ERP_CTR.h"
#include "Display01.h"

//#undef CROSSTABMAP
#define CROSSTABMAP 1


int CrOrLf ( int c )
{
	return ( c == '\r' ) || ( c == '\n' ) || ( c == '\t' ) ? c : 0;
};


int PCRE_Replace ( String& where, String s_from, String s_to )
{
	RegExp r0 ( "(.*)" + s_from + "(.*)", RegExp::MULTILINE );

	while ( r0.GlobalMatch ( where ) )
	{
		if ( r0.GetCount() == 2 )
		{
			where = r0[0] + s_to + r0[1];
			return 0;
		}

		else
		{
			return 1;
		}
	}
//	return 0;
}



ERP_CTR::~ERP_CTR()
{
	DUMP ( FixedColGrid.GetColumnWidths() );
	DUMP ( sp1.GetPos() );

	confgXmlFile.ColumnWidth = FixedColGrid.GetColumnWidths();
	confgXmlFile.SpliterWidth = sp1.GetPos();

	StoreAsXMLFile ( confgXmlFile, "ConfgXml", path );

	//oracle_conn.Logoff();
	psql_session.Close();
}



ERP_CTR::ERP_CTR()
{
	CtrlLayout ( *this, "PRAGATI Reports System" );

	SetDateFormat ( "%3:02d/%2:02d/%1:04d" );
	SetDateScan ( "dmy" );
	//UseHomeDirectoryConfig(true);
	DUMP ( GetHomeDirectory() );

	CtrlLayout ( Reports );
	CtrlLayout ( Select );
	CtrlLayout ( Process );
	CtrlLayout ( Details );

	tab1.Add ( Reports, "Reports" );
	tab1.Add ( Select, "Select" );
	tab1.Add ( Details, "Orders" );
	tab1.Add ( Process, "Report" );

	Process.Add ( sp1.VSizePos ( 30 ) );
	sp1.Horz ( FixedColGrid, ProcessGrid );
	sp1.SetPos ( 2500 );
	Process.VSizePos ( 100 ).HSizePos();
	Process.SizePos();

	Details.SizePos();

	AddFrame ( status );
	
	

	SetTimeCallback ( 200, THISBACK ( OpenDB ) );
		
	Reports.btnOK <<= THISBACK ( XMLLoad );

	Select.btnProceed <<= THISBACK ( Proceed );

	ProcessGrid.sby.WhenAction = THISBACK ( Scroll_Fun ); //Scroll in the library made as public from private

	FixedColGrid.WhenLeftClick = THISBACK ( Sync_Cursor );

	FixedColGrid.WhenMenuBar = THISBACK ( myBar );
	FixedColGrid.WhenSort = THISBACK ( Sort1x );


	Process.btnCsv <<= THISBACK ( Save_Grid );
	Process.btnClear <<= THISBACK ( Clear_Sel );

	FixedColGrid.find.WhenEnter = THISBACK ( SyncProcess );
	ProcessGrid.find.WhenEnter = THISBACK ( SyncProcess1 );

	FixedColGrid.WhenMenuBar = THISBACK ( myBar );

	ProcessGrid.WhenLeftClick = THISBACK ( Sync_Cursor_Fixed );

	FixedColGrid.sby.WhenAction = THISBACK ( Scroll_Fixed );

	ProcessGrid.Absolute();

	ProcessGrid.sbx.AutoHide ( true );

	Details.OracleGrid.Absolute().sbx.AutoHide();

	FixedColGrid.Absolute().sbx.AutoHide ( true );

	Select.btnProceed.Disable();

	ProcessGrid.Ready ( false );

	ProcessGrid.Editing();
	//ProcessGrid.Sorting(true);
	ProcessGrid.GridColor ( Black() );

	ProcessGrid.Searching();
	ProcessGrid.SetToolBar();
	FixedColGrid.GridColor ( Black() );
	FixedColGrid.Searching();
	FixedColGrid.SetToolBar();

	Details.OracleGrid.Searching();
	Details.OracleGrid.SetToolBar();
	Details.OracleGrid.MultiSelect ( true ).Clipboard ( true ).CopyColumnNames ( true ).Inserting ( false ).Appending ( false ).ClipboardCut ( false );
//	Details.OracleGrid.Clipboard();

	Sizeable().Zoomable();

//	XMLLoad();


	Process.drpItemID.Hide();
	Process.drpPartyName.Hide();

	pi.Title ( "Processing data ..." );
	//tab1.Set ( 1 );
}


void ERP_CTR::myBar ( Bar &bar )
{

	bar.Add ( "Details by Name", CtrlImg::information(), THISBACK ( ShowByName ) );
	bar.Add ( "Details by Item ID", CtrlImg::information(), THISBACK ( ShowByItemID ) );
	FixedColGrid.StdMenuBar ( bar );

}


void ERP_CTR::SyncProcess()
{
	ProcessGrid.find.SetText ( FixedColGrid.find.GetText() );
	ProcessGrid.find.Action();

}

void ERP_CTR::SyncProcess1()
{
	FixedColGrid.find.SetText ( ProcessGrid.find.GetText() );
	FixedColGrid.find.Action();

}

void ERP_CTR::ShowByName()
{

	Point u1 = Details.OracleGrid.GetCursorPos();
	DUMP ( u1 );
	Details.OracleGrid.find.SetText ( AsString ( FixedColGrid ( 0 ) ) );
	Details.OracleGrid.find.Action();
	tab1.Set ( 0 );
}

void ERP_CTR::ShowByItemID()
{
	Point u1 = Details.OracleGrid.GetCursorPos();
	DUMP ( u1 );
	Details.OracleGrid.find.SetText ( AsString ( FixedColGrid ( 1 ) ) );
	Details.OracleGrid.find.Action();
	tab1.Set ( 0 );
}

void ERP_CTR :: Scroll_Fun()
{
	int u1 = ProcessGrid.sby.Get();
	FixedColGrid.sby.Set ( u1 );
}

void ERP_CTR :: Scroll_Fixed()
{
	int u1 = FixedColGrid.sby.Get();
	ProcessGrid.sby.Set ( u1 );
}


void ERP_CTR :: Sync_Cursor()
{

	Point u2 = FixedColGrid.GetCursorPos();
//	ProcessGrid.GetRow(u2.y).Bg(LtGreen());
	ProcessGrid.SetCursor ( u2.y );
//	ProcessGrid.GetRow(u2.y).Fg(Blue());
//	ProcessGrid.GetRow(b).SetFont(Roman().Bold());
}

void ERP_CTR :: Sync_Cursor_Fixed()
{

	Point u2 = ProcessGrid.GetCursorPos() ;
	FixedColGrid.SetCursor ( u2.y );
//	FixedColGrid.GetRow(u2.y).Bg(LtGreen());

}


void ERP_CTR :: Show_By_Name()
{

	ProcessGrid.find.SetText ( AsString ( Process.drpPartyName.GetValue() ) );
	FixedColGrid.find.SetText ( AsString ( Process.drpPartyName.GetValue() ) );
	ProcessGrid.find.Action();
	FixedColGrid.find.Action();
}

void ERP_CTR :: Show_By_ItemID()
{

	ProcessGrid.find.SetText ( AsString ( Process.drpItemID.GetValue() ) );
	FixedColGrid.find.SetText ( AsString ( Process.drpItemID.GetValue() ) );
	ProcessGrid.find.Action();
	FixedColGrid.find.Action();

}

void ERP_CTR ::Clear_Sel()
{
	ProcessGrid.find.Clear();
	FixedColGrid.find.Clear();
	ProcessGrid.find.Action();
	FixedColGrid.find.Action();
	Process.drpItemID.Clear();
	Process.drpPartyName.Clear();
	Fill_Drop_List();
	//Drop_Fill_Party();
	//Drop_Fill_Item();

}

void ERP_CTR::Sort1x()
{
	static int bSortOrder[4];

	int iCol = FixedColGrid.GetMouseCol ( FixedColGrid.leftpnt );
	iCol--;

	if ( iCol > -1 )
	{


		bSortOrder[iCol] = ( bSortOrder[iCol] == 1 ) ? 2 : 1 ;
		FixedColGrid.Sort ( iCol, bSortOrder[iCol] );
		ProcessGrid.Sort ( iCol, bSortOrder[iCol] );
	}

	LOG ( "Col : " << iCol << " |  SortOrder : " << bSortOrder[iCol] );
}

void ERP_CTR :: Save_Grid()
{
	FileSel fSelOut ;
	String filename, strSaveData ;
	fSelOut.Type ( "CSV", "*.csv" );

	if ( ! fSelOut.ExecuteSaveAs() )
	{
		PromptOK ( "File is already exists !!!\nFile not Saved !!!" );
		return;
	}

	filename = ~fSelOut;

	fOut1.Open ( filename );

	fOut1.PutLine ( HeaderInfo );

	for ( int col_no = 0; col_no < ProcessGrid.GetColumnCount(); col_no++ )
	{
		strSaveData << ProcessGrid.GetColumnName ( col_no )  << ";";
	}

	fOut1.PutLine ( strSaveData );

	strSaveData.Clear();

	for ( int row_no = 0; row_no < ProcessGrid.GetCount(); row_no++ )
	{
		for ( int col_no = 0; col_no < ProcessGrid.GetColumnCount(); col_no++ )
		{

			strSaveData << ProcessGrid.Get ( row_no, col_no ) << ";";

		}

		fOut1.PutLine ( strSaveData );

		strSaveData.Clear();
	}

	fOut1.Close();
}

void ERP_CTR::OpenDB()
{
	QTFDESIGN.Clear();
	Pqry.Clear();
	String Pqry;
	String ColName;
	SqlColumnInfo sqlInf;
	int ColCount, rowcnt = 0;

	Pqry = " Select qtfreportname  from qtflnreportdesign";
	
	
	#ifdef PLATFORM_LINUX
//	if ( psql_session.Open ( "host=192.168.79.45 dbname=papl_lnreports user=reportuser password=[UserReports]" ) )
	if ( psql_session.Open ( "host=192.168.79.55 dbname=papl_lnreports user=reportuser password=[UserReports]" ) )
	#else	
	//if(psql_session.Open("host=192.168.79.45 dbname=papl_lnreports user=reportuser password=[UserReports]"))
	if(psql_session.Open("postgres://reportuser:[UserReports]@192.168.79.55:5432/papl_lnreports"))
	#endif	
	{

#ifdef _DEBUG
	//	psql_session.SetTrace();
#endif


		pConnected = true ;
	}

	if ( pConnected )
	{
		LOG ( "PostgreSQL Connected" );
		Sql sqlPSQL ( psql_session );



		if ( sqlPSQL.Execute ( Pqry ) )
		{
			for ( ;; )
			{
				Vector<Value>rowdata;

				if ( !sqlPSQL.Fetch ( rowdata ) )
				{
					break;
				}

				else
				{
					//	DUMP ( rowdata );
					for ( int i = 0; i < rowdata.GetCount(); i++ )
					{
//						DUMP ( rowdata[i] );

						//	Add ( dl.HSizePos().TopPos ( 5, Ctrl::STDSIZE ) );
						Reports.dl.Add ( rowdata[i] );
						Reports.dl.WhenAction = THISBACK ( drplst );
						//dl<< THISBACK ( drplst );

					}

					if ( Reports.dl.GetCount() > 0 )
						Reports.dl.SetIndex ( 0 );
					
				
					
				}

			}

		}
	}
	else
	{
		Exclamation ( Format ( "Error in open: %s", DeQtf ( psql_session.GetLastError() ) ) );

	}
	
	
}

void ERP_CTR::drplst()

{
		
	QTFDESIGN.Clear();
//	OpenDB();
	QTFREPORTNAME = Reports.dl.GetData();
	DUMP ( QTFREPORTNAME );
	//	DUMP(dl.GetData());
	Pqry.Clear();
	Pqry = "Select xmldesign from qtflnreportdesign where qtfreportname = '" << QTFREPORTNAME << "'";
	DUMP ( Pqry );

	if ( pConnected )
	{
		LOG ( pConnected );
		Sql sqlPSQL ( psql_session );

		if ( sqlPSQL.Execute ( Pqry ) )
		{
			//Vector<Value>rowdata1;

			if ( sqlPSQL.Fetch ( rowdata1 ) )
			{
//				DUMP ( rowdata1 );
			//	QTFDESIGN.Clear();
				QTFDESIGN << rowdata1;
				QTFDESIGN.Replace ( "[", "" );
				QTFDESIGN.Replace ( "]", "" );
//				DUMP ( QTFDESIGN );

				//	Reports.ok <<= THISBACK(XMLLoad);
				//qDat.LoadXML ( QTFDESIGN );
			}

			else
			{
				PromptOK ( "Error while executing Pqry" );
			}
			
				for ( int i = 0; i < qDat.repData.RepHashVars.GetCount() ; i++ )
					{
						label[i].Hide();
						drplist[i].Hide();
					}
		}
	}
}


void ERP_CTR:: XMLLoad()
{
	

//	qDat.LoadXML ( QTFDESIGN );
//	DUMP(qDat.repData.strReportName);

	
	if(qDat.repData.strReportName.GetLength()>0) Title(qDat.repData.strReportName);
	
	//String ConfgXml,path;
	//QTFREPORTID = "Conf";

	ConfgXml = QTFREPORTNAME + ".xml";
//	DUMP ( ConfgXml );

	path = GetAppDataFolder() + "/ERP_CTR/";
//	DUMP ( path );
	RealizeDirectory ( path );
	path = path + QTFREPORTNAME + ".xml";
//	DUMP ( path );
//	StoreAsXMLFile ( confgXmlFile, "ConfgXml", path );
	checkfile = LoadFromXMLFile ( confgXmlFile, path );
//	DUMP ( checkfile );

	//StoreAsXMLFile(confgXmlFile,"ConfgXml",path);

	//path = GetAppDataFolder() + "/ConfgXml/" + ConfgXml + ".cfg" ;

	qDat.LoadXML ( QTFDESIGN );
	int Y = 16;
	bool firstqry = true;
	for ( int i = 0; i < qDat.repData.RepHashVars.GetCount() ; i++ )
	{
			
		drplist[i].Clear();
		String Name, HashName;
		Name.Clear();
		Name = qDat.repData.RepHashVars[i].DropListCols;
		DUMP ( Name );
		

		if ( Name.StartsWith ( "DATE_" ) )
		{
			
		//	label[i].Enable(true);
			Select.Add ( label[i].SetLabel ( Name ).LeftPosZ ( 16, 96 ).TopPosZ ( Y, 23 ) );
			Select.Add ( drpDate[i].LeftPosZ ( 128, 140 ).TopPosZ ( Y, 24 ) );
			drpDate[i].Enable();
			Y = Y + 50;
		}

		else
		{
			label[i].Show(true);
			drplist[i].Show(true);	
		//	label[i].Enable(true);	
			Select.Add ( label[i].SetLabel ( Name ).LeftPosZ ( 16, 96 ).TopPosZ ( Y, 23 ) );
			Select.Add ( drplist[i].LeftPosZ ( 128, 140 ).TopPosZ ( Y, 24 ) );
			
			Y = Y + 50;
		
			
			drplist[i].WhenAction = THISBACK1(SelectDrpList,i); //callback function when selected droplist
			
			
			if(firstqry == true)
			{
			if ( pConnected )
			{
				//	LOG ( pConnected );
				
				String query;
				query.Clear();
				query = qDat.repData.RepHashVars[i].HashVarQuery;
			
				query = Join ( Split ( query, CrOrLf ), " " );
			
				Sql sqlPSQL ( psql_session );
			
				if ( sqlPSQL.Execute ( query ) )
				{
					//	DUMP(query);
					
					while ( sqlPSQL.Fetch() )
					{
								
							drplist[i].Add ( sqlPSQL[0] );
							drplist[i].SetIndex(0);
					}
						
										
				}
					
				
			}
						
			firstqry = false;
			}
		}
	
		
	}
	
	Select.btnProceed.Enable();
	

}



void ERP_CTR::SelectDrpList(int id)
{
                                
	for ( int p = id; p < qDat.repData.RepHashVars.GetCount(); p++ )
	{
		DUMP(p);
		String Name, HashName;
		
		Name = qDat.repData.RepHashVars[p].DropListCols;
		HashName = qDat.repData.RepHashVars[p].HashVarName;
		DUMP(HashName);
		if(p == id)
		{
		
			int find = RepVars.Find(HashName);
			
			if(find >= 0)
			{
				RepVars.Remove(find);
				RepVars.Insert(find,HashName,drplist[p].GetData());
			}
			else
			{
			
				DUMP(drplist[p].GetData());
			RepVars.Add(HashName,drplist[p].GetData());
			DUMP(RepVars);
			}
		}
		
		else
		if ( Name.StartsWith ( "DATE_" ) )
		{
				//nothing to do
		}
		
		else
			
			{
			
			String query;
				query.Clear();
				query = qDat.repData.RepHashVars[p].HashVarQuery;
				
				query = Join ( Split ( query, CrOrLf ), " " );
				
				DUMP(RepVars.GetCount());
				for(int q=0;q<RepVars.GetCount();q++)
				{
					
					
					query.Replace(RepVars.GetKey(q),RepVars[q]);
			
				}
					
				if(pConnected)
				{	
						LOG("Connected");
						Sql sqlPSQL ( psql_session );
				if ( sqlPSQL.Execute ( query ) )
				{
					
					drplist[p].Clear();

					while ( sqlPSQL.Fetch() )
					{
						drplist[p].Add ( sqlPSQL[0] );
						drplist[p].SetIndex(0);
					}
				
					drplist[p].Enable();
				}
			
				}
			}
	}


}


void ERP_CTR :: Proceed()
{

	myQuery.Clear();
	dropFilterId.Clear();
	FixedColId.Clear();
	processgridcols.Clear();
	Maximize ( true );
	myQuery = Join ( Split ( qDat.repData.strDataSQL, CrOrLf ), " " );
	DUMP(myQuery);
	HeaderInfo.Clear();
	HeaderInfo << "ReportName" << " : " << qDat.repData.strReportName << "\n";
	HeaderInfo << "SysDateTime" << " : " << GetSysTime() << "\n";

	for ( int i = 0; i < qDat.repData.RepHashVars.GetCount(); i++ )
	{
		String Name, HashName;
		Name = qDat.repData.RepHashVars[i].DropListCols;
		HashName = qDat.repData.RepHashVars[i].HashVarName;
		DUMP ( HashName );
	//	DUMP(Name);
		int val;
	
		if ( Name.StartsWith ( "DATE_" ) )
		{

			SetDateFormat ( "%3:02d-%2:MON-%1:04d" );

			From_Date.Clear();
			From_Date << drpDate[i].GetData();
			HeaderInfo << Name << " : " << From_Date << "\n";

			if ( ! ( From_Date.IsEmpty() ) )
			{
				RegExp regx;
				regx.SetPattern("("+HashName+")");
				
				String data1;
				data1.Clear();
				data1 << "(" << From_Date << ")" ;
				regx.ReplaceGlobal(myQuery,data1);//,true);
			}

			else
			{
				PromptOK ( "Please select Date " );

			}

			SetDateFormat ( "%3:02d/%2:02d/%1:04d" );

		}
	
		else
		{
			
			String data;
			data.Clear();
			data = drplist[i].GetData();
		//	DUMP(data);
			HeaderInfo << Name << " : " << data << "\n";
			if ( ! ( data.IsEmpty() ) )
			{
		
				RegExp regx;
				regx.SetPattern("("+HashName+")");
				
				String data1;
				data1.Clear();
				data1 << "(" << data << ")" ;
				DUMP(data1);
				regx.ReplaceGlobal(myQuery,data1);//,true);
				DUMP(myQuery);
			}

			else
			{
				String msg = "Please select " + Name;
				PromptOK ( msg );
			}
		}
	}

	fill_oracle_data();

	//Maximize(true);

}

void ERP_CTR::fill_oracle_data()
{
	int i, j, boldfnt;

	Details.OracleGrid.Reset();
	Details.OracleGrid.Ready ( false );

	CrossTab.Clear();
	qtycol.Clear();
	uniqcol.Clear();
	drplistcol.Clear();
	FixedColId.Clear();
	EndColId.Clear();
	dropFilterId.Clear();

	LastRow = 0 ;

	LOG ( "Start : " << double ( GetTickCount() ) / 1000.0 << "\n" );
//	DUMP ( myQuery );

	if ( pConnected )
	{
			LOG ( pConnected );
		Sql sqlPSQL ( psql_session );

		if ( sqlPSQL.Execute ( myQuery ) )
		{
			ColCount = sqlPSQL.GetColumns();

			DUMP(ColCount);
			for ( i = 0 ; i < ColCount; i++ )

			{

				SqlInf = sqlPSQL.GetColumnInfo ( i );
				colName.Set ( i, SqlInf.name );
				DUMP ( colName[i] );

				for ( j = 0; j < qDat.repData.SumCols.GetCount();j++ )
				{

					if ( colName[i] == qDat.repData.SumCols[j] )
					{

						qtycol.Add() = i;
						LOG ( "SumCol : " << colName[i] << "  : " << i );

					}
				}

				if ( colName[i] == qDat.repData.strHeaderCol )
					weekcol = i;

				for ( j = 0; j < qDat.repData.UniqueCols.GetCount();j++ )
				{

					if ( colName[i] == qDat.repData.UniqueCols[j] )
					{

						uniqcol.Add() = i;
						LOG ( "UniqCol : " << colName[i] << "  : " << i );
					}
				}


				for ( j = 0; j < qDat.repData.RepHashVars.GetCount() ;j++ )
				{

					if ( colName[i] == qDat.repData.RepHashVars[j].DropListCols )
					{

						drplistcol.Add() = i;

					}
				}

				for ( j = 0; j < qDat.repData.EndCols.GetCount() ;j++ )
				{

					if ( colName[i] == qDat.repData.EndCols[j] )
					{

						EndColId.Add() = i;

					}
				}

				Details.OracleGrid.AddColumn ( colName[i] , 100 );

			}

			for ( j = 0; j < qDat.repData.FixedCols.GetCount();j++ )
			{

				for ( i = 0; i < ColCount; i++ )
				{
					if ( colName[i] == qDat.repData.FixedCols[j] )
					{

						FixedColId.Add() = i;
					LOG ( "FixedCol : " << colName[i] << "  : " << i );

					}
				}


			}

			for ( j = 0; j < qDat.repData.dropFilters.GetCount();j++ )
			{
				for ( i = 0; i < qDat.repData.FixedCols.GetCount();i++ )
				{
					if ( qDat.repData.dropFilters[j].FilterColName == qDat.repData.FixedCols[i] )
					{
						dropFilterId.Add() = i;
					}
				}
			}


			LOG ( "Processed Query : " << double ( GetTickCount() ) / 1000.0 << "\n" );

			int iCnt1 = 0 ;

			for ( ;; )
			{

				Vector<Value> row;


				if ( !sqlPSQL.Fetch ( row ) )
					break;

				Details.OracleGrid.Add ( row );

				iCnt1++;

				if ( ( iCnt1 % 1000 ) == 0 )
				{
					strStat.Clear();
					strStat << "Rows Loaded : " << iCnt1 ;

					pi.SetText ( strStat );

				}
			}

			LOG ( "Filled Grid : " << double ( GetTickCount() ) / 1000.0 << "\n" );

			pi.SetText ( "Sort by Week" );
			Details.OracleGrid.Sort ( weekcol, 1 );

			DUMP ( Details.OracleGrid.GetRowCount() );

			Details.OracleGrid.Ready ( true );
			dataRows = Details.OracleGrid.GetRowCount() ;

			strStat.Clear();
			strStat << "DB Rows : " << dataRows ;
			status.Set ( strStat );
			status.RefreshFrame();

			Details.OracleGrid.GoBegin();
			Details.OracleGrid.Ready ( true );

			LOG ( "Processing starts : " << double ( GetTickCount() ) / 1000.0 << "\n" );

			Process_data();



			LOG ( "Finish Processing data : " << double ( GetTickCount() ) / 1000.0 << "\n" );

			for ( boldfnt = 0; boldfnt < ProcessGrid.GetCount(); boldfnt++ )
			{
				ProcessGrid.GetRow ( boldfnt ).SetFont ( Roman().Bold() );
			}

			tab1.Set ( 2 );

			Party_No = 0;
			Item_No = 0;

			Process.drpPartyName <<= THISBACK ( Show_By_Name );

			Process.drpItemID <<= THISBACK ( Show_By_ItemID );
			LOG ( "Drop_Compare Start : " << double ( GetTickCount() ) / 1000.0 );
			//Drop_Fill_Party();
			//Drop_Fill_Item();
			Fill_Drop_List();
			LOG ( "Drop_Compare End : " << double ( GetTickCount() ) / 1000.0 );


			DUMP ( Details.OracleGrid.GetCount() );

		}
	}

	else
	{
		PromptOK ( "Error in SQLQuery" );

	}

}



void ERP_CTR :: Date_As_Column()
{
	int week_col_add, i, j, z, q, s;
	Value week_no, old_week_no ;
	String  date_string1 , sumcol_string;

	q = qDat.repData.SumCols.GetCount();
	i = qDat.repData.FixedCols.GetCount() + 1;
	j = i + ( qDat.repData.SumCols.GetCount() - 1 );
	FixedColGrid.AddRow();

	for ( week_col_add = 0;week_col_add < Details.OracleGrid.GetCount();week_col_add++ )
	{

		date_string1.Clear();
		week_no =  Details.OracleGrid.Get ( week_col_add, weekcol );
		date_string1 << week_no;

		if ( old_week_no != week_no )
		{
			for ( int k = 0;k < qDat.repData.SumCols.GetCount();k++ )
			{
				ProcessGrid.AddColumn ( date_string1, 45 ).AlignCenter().HeaderAlignCenter();
				processgridcols.Add ( date_string1 );
			}

			ProcessGrid.JoinFixedCells ( i, 0, j, 0 );


			Week_Data.Add ( date_string1 );


			old_week_no = week_no;
			i = i + qDat.repData.SumCols.GetCount();
			j = j + qDat.repData.SumCols.GetCount();

		}

	}

	for ( s = FixedColGrid.GetColumnCount() ; s < ProcessGrid.GetColumnCount(); ( s = s + q ) )
	{

		for ( int p = 0; p < qDat.repData.SumCols.GetCount() ; p++ )
		{

			sumcol_string <<  qDat.repData.SumCols[p];
			z = s + p;
			ProcessGrid.Set ( 0, z , sumcol_string ); // C
			sumcol_string.Clear();

		}

	}


	
	ProcessGrid.SetFixedRows ( 2 );

	FixedColGrid.SetFixedRows ( 2 );

}

void ERP_CTR::Fill_Drop_List()
{
	Process.drpPartyName.Clear();
	Process.drpItemID.Clear();

	for ( int i = 0;i < dropFilterId.GetCount();i++ )
	{
		Value sLast = "" , val;
		bool AltClr = true;


		ProcessGrid.Sort ( i, 1 );


		for ( int Drop_col_add = 0;Drop_col_add < ProcessGrid.GetCount();Drop_col_add++ )
		{

			val = ProcessGrid.Get ( Drop_col_add, dropFilterId[i] );
//			DUMP ( val );
//			DUMP ( sLast );

			if ( val != sLast )
			{

				//AltClr =  AltClr ? false : true ;


				//if ( AltClr )
				//{
				if ( i == 0 )
					Process.drpPartyName.Add ( val );
				else
					if ( i == 1 )
						Process.drpItemID.Add ( val );

				//}

				sLast = val ;
			}

		}

		if ( i == 0 )
		{
			Process.lb1.SetLabel ( qDat.repData.dropFilters[i].FilterName );
			Process.drpPartyName.Show();
		}

		else

			if ( i == 1 )
			{
				Process.lb2.SetLabel ( qDat.repData.dropFilters[i].FilterName );
				Process.drpItemID.Show();
			}

		ProcessGrid.ClearSort();

	}

	ProcessGrid.Sorting ( false );
}

void ERP_CTR::Drop_Fill_Party()
{
	Value sLast = "" , val;
	bool AltClr = true;

	Process.drpPartyName.Clear();


	ProcessGrid.Sort ( 0 );


	for ( int Drop_col_add = 0;Drop_col_add < ProcessGrid.GetCount();Drop_col_add++ )
	{

		val = ProcessGrid.Get ( Drop_col_add, dropFilterId[0] );

		if ( val != sLast )
		{

			AltClr =  AltClr ? false : true ;


			if ( AltClr )
			{
				Process.drpPartyName.Add ( val );
			}

			sLast = val ;
		}

	}


	ProcessGrid.ClearSort();
}

void ERP_CTR::Drop_Fill_Item()
{
	Value sLast = "" , val;
	bool AltClr = true;
	Process.drpItemID.Clear();
	ProcessGrid.Sort ( 1 );

	for ( int Drop_col_add = 0;Drop_col_add < ProcessGrid.GetCount();Drop_col_add++ )
	{

		val = ProcessGrid.Get ( Drop_col_add, dropFilterId[1] );

		if ( val != sLast )
		{

			AltClr =  AltClr ? false : true ;


			if ( AltClr )
			{
				Process.drpItemID.Add ( val );
			}

			sLast = val;
		}
	}

	ProcessGrid.ClearSort();

}

String ERP_CTR::Calc ( String ss )
{
	EscValue v = Evaluatex ( ss, vars );
	String txt;
	txt =  v.ToString();
	return txt;
}

void ERP_CTR::Process_data()
{
	FixedColGrid.Reset();
	ProcessGrid.Reset();
	Week_Data.Clear();

	pi.SetTotal ( dataRows );
	strStat.Clear();
	strStat << "Num of data rows : " << dataRows ;

	pi.SetText ( strStat );


	int  process_row, out_row, week_set_row = 0;
	bool Can_Add_Row;
	int Column_no, u, v , q;
	String week;


	u = 0;
	v = 0;

	if ( checkfile )
	{
		sp1.SetPos ( confgXmlFile.SpliterWidth );

		FixedColGridWidth = confgXmlFile.ColumnWidth;
		DUMP ( FixedColGridWidth );

		Vector<int> wid;
		Vector<String> width = Split ( FixedColGridWidth, ' ' );
		FixedColGrid.Absolute();
		FixedColGrid.ResizeColMode ( 1 );
		FixedColGrid.Ready ( false );
		ProcessGrid.Ready ( false );

		for ( int w = 0;w < width.GetCount();w++ )
		{
			wid.Add ( StrInt ( width[w] ) );
		}

		for ( int i = 0 ; i < FixedColId.GetCount() ; i++ )
		{
			int ix1 = FixedColId[i];

			if ( wid.GetCount() <= i )
			{
				wid.Add ( 150 );
			}

			DUMP ( wid[i] );

			FixedColGrid.AddColumn ( colName[ix1], wid[i] );

			ProcessGrid.AddColumn ( colName[ix1], 1 );

		}

		FixedColGrid.Ready ( true );

		ProcessGrid.Ready ( true );
	}

	else
	{
		sp1.SetPos ( 4000 );

		for ( int i = 0 ; i < FixedColId.GetCount() ; i++ )
		{
			int ix1 = FixedColId[i];

			FixedColGrid.AddColumn ( colName[ix1], 150 );

			ProcessGrid.AddColumn ( colName[ix1], 1 );

		}

	}

	for ( int i = 0 ; i < FixedColId.GetCount() ; i++ )
	{
		int ix1 = FixedColId[i];
		processgridcols.Add ( colName[ix1] );
	}

	Date_As_Column();


	for ( int i = 0 ; i < qDat.repData.TotalColNames.GetCount() ; i++ )
	{
		String name =  qDat.repData.TotalColNames[i];
		ProcessGrid.AddColumn ( name ).WrapText();
		processgridcols.Add ( name );
		//colName.Add(name);
	}

	for ( int i = 0 ; i < qDat.repData.calcFormulas.GetCount() ; i++ )
	{
		String name =  qDat.repData.calcFormulas[i].ColName;
		ProcessGrid.AddColumn ( name ).WrapText();
		//colName.Add(name);
	}


	for ( int i = 0 ; i < EndColId.GetCount() ; i++ )
	{
		int ix1 = EndColId[i];

		ProcessGrid.AddColumn ( colName[ix1], 100 );

	}

	//ProcessGrid.AddColumn ( "Bal", 100 );

	ProcessGrid.Ready ( true );

	dataRows = Details.OracleGrid.GetCount() ;


	for ( process_row = 0; process_row < dataRows ;process_row++ )
	{

		Can_Add_Row = true ;

		RTIMING ( "Process Row" );

//Check and add itemid

		String strProcRow = "";
		int ucol1;

		for ( int j = 0; j < qDat.repData.UniqueCols.GetCount();j++ )
		{
			ucol1 = uniqcol[j];
			strProcRow << Details.OracleGrid.Get ( process_row, uniqcol[j] );
		}

		int iRes = CrossTab.Find ( strProcRow );

		if ( iRes > -1 )
		{
			Can_Add_Row = false ;
			week_set_row = iRes ;
		}

		if ( Can_Add_Row )

		{
			week_set_row = 	FixedColGrid.GetCount();

		/*	for ( int j = 0;j < qDat.repData.FixedCols.GetCount();j++ )
			{

				FixedColGrid.Set ( week_set_row, j, Details.OracleGrid.Get ( process_row, j ) );

				ProcessGrid.Set ( week_set_row, j, Details.OracleGrid.Get ( process_row, j ) );

			}*/

			for ( int j = 0 ; j < FixedColId.GetCount() ; j++ )
			{
				int ix1 = FixedColId[j];

				FixedColGrid.Set ( week_set_row, j, Details.OracleGrid.Get ( process_row, ix1 ) );

				ProcessGrid.Set ( week_set_row, j, Details.OracleGrid.Get ( process_row, ix1 ) );
			}

			for ( int p = 0; p < EndColId.GetCount(); p++ )
			{
				int ix2 = EndColId[p];
//				DUMP ( ix2 );
				int fixed_Week_cnt = qDat.repData.FixedCols.GetCount() + ( Week_Data.GetCount() * qDat.repData.SumCols.GetCount() ) + qDat.repData.TotalColNames.GetCount() + qDat.repData.calcFormulas.GetCount() + p ;
//				DUMP ( fixed_Week_cnt );
				ProcessGrid.Set ( week_set_row, fixed_Week_cnt , Details.OracleGrid.Get ( process_row, ix2 ) );

			}

			CrossTab.Add ( strProcRow, week_set_row );
		}

		week.Clear();

		week << Details.OracleGrid.Get ( process_row, weekcol ) ;

		for ( int out_col = 0; out_col < ProcessGrid.GetColumnCount(); out_col++ )
		{

			RTIMING ( "Search Week" );

			if ( week ==  Week_Data[out_col] )
			{

				Column_no = out_col * qDat.repData.SumCols.GetCount() + qDat.repData.FixedCols.GetCount() ;

				break;
			}

		}


		for ( int j = 0; j < qDat.repData.SumCols.GetCount(); j++ )
		{
			q = Column_no + j	;
			u = ProcessGrid.Get ( week_set_row, q );

			if ( u > 0 )
			{
				v = Details.OracleGrid.Get ( process_row, qtycol[j] );

				u = u + v;


				ProcessGrid.Set ( week_set_row, q , u );

			}

			else
			{
				ProcessGrid.Set ( week_set_row, q, Details.OracleGrid.Get ( process_row, qtycol[j] ) );
			}

		}

		if ( ( process_row % 1000 ) == 0 )
		{
			strStat.Clear();
			strStat << "Processed : " << process_row << " of " << dataRows ;

			pi.SetText ( strStat );
			pi.SetPos ( process_row );
//			LOG ( " " << strStat << "  -- Time : " << double ( GetTickCount() ) / 1000.0 << "\n" );

		}

	}

	int x;


	for ( int processRows = 0; processRows < ProcessGrid.GetCount(); processRows++ )
	{
		//	DUMP ( processRows );

		for ( int j = 0; j < qDat.repData.SumCols.GetCount(); j++ )
		{
			int setcolno =   qDat.repData.FixedCols.GetCount() + ( Week_Data.GetCount() * qDat.repData.SumCols.GetCount() )  + j;

			for ( int weekCnt = 0; weekCnt < Week_Data.GetCount(); weekCnt++ )

			{
				Column_no = weekCnt * qDat.repData.SumCols.GetCount() + qDat.repData.FixedCols.GetCount() + j ;

				x = ProcessGrid.Get ( processRows, Column_no );
				//int setcolno =   qDat.repData.FixedCols.GetCount() + ( Week_Data.GetCount() * qDat.repData.SumCols.GetCount() )  + j;
				int z = ProcessGrid.Get ( processRows, setcolno );
				//DUMP(z);

				if ( z > 0 )
				{
					if ( x < 0 )
						x = 0;

					z = x + z;

					//DUMP(z);
					ProcessGrid.Set ( processRows, setcolno, z );
				}

				else
				{
					ProcessGrid.Set ( processRows, setcolno, x );
					//DUMP(x);
				}

			}
		}

		//////////////Formula//////////

		for ( int c = 0;c < qDat.repData.calcFormulas.GetCount();c++ )
		{
			VectorMap<String, int> VColNum;

			RegExp r1 ( "#(\\w+)#", RegExp::UNICODE );
			int i = 0;
			String r;

			while ( r1.GlobalMatch ( qDat.repData.calcFormulas[c].Formula ) )
			{
				for ( int i = 0; i < r1.GetCount(); i++ )
				{
					r.Clear();
					r << r1[i];

					for ( int cc = 0;cc < processgridcols.GetCount();cc++ )
					{
//						DUMP ( processgridcols[cc] );
//						DUMP ( r );

						if ( processgridcols[cc] == r )
						{
							VColNum.Add ( r, cc );
						}

					}

				}
			}

			if ( r1.IsError() )
				r << r1.GetError() << '\n';

			String where;

			where = qDat.repData.calcFormulas[c].Formula;

			for ( int l = 0;l < VColNum.GetCount();l++ )
			{
				String from;
//				DUMP ( where );
				from << "(" << "#" <<  VColNum.GetKey ( l ) << "#" << ")";
//				DUMP ( from );
				int colnum = VColNum[l];
//				DUMP ( colnum );

				String to1 = FormatInt ( ProcessGrid.Get ( processRows, colnum ) );
				String to;

				if ( to1.IsEmpty() )
					to = "(0)";
				else to = "(" + to1 + ")";

				RegExp regx;
				regx.SetPattern(from);
				regx.ReplaceGlobal(where,to);

				PCRE_Replace ( where, from, to );
			}

//			DUMP ( where );

			String CalcRes = Calc ( where );
			int cnt = qDat.repData.FixedCols.GetCount() + ( Week_Data.GetCount() * qDat.repData.SumCols.GetCount() )  + qDat.repData.TotalColNames.GetCount() + c;
			ProcessGrid.Set ( processRows, cnt, CalcRes );
		}
	}

	strStat.Clear();

	strStat << "Processed : " << dataRows << " of " << dataRows ;
	status.Set ( strStat );

	pi.Close();

}

void ERP_CTR::Serialize ( Stream &s )
{
	//s % sp1 ;
}

GUI_APP_MAIN
{
	ERP_CTR mrp;
	String path1 = GetAppDataFolder() + "\\ERP_CTR\\" ;
	RealizeDirectory ( path1 );
	path1 = path1 + "ERP_CTR" + ".cfg";
	LoadFromFile ( mrp, path1 );
	mrp.Run();
	StoreToFile ( mrp, path1 );
}
