/*-----------------------------------------------------------------------*\
| COMPONENT:																				  |
|	Product: 	Windows API for Magic  Ver 8.30									  |
|	Package: 	MCF_API																	  |
|	File	 : 	UserInterface.cpp :													  |
|					  Defines User Interface for the application.				  |
| ABSTRACT: 																				  |
|	File contains example of API. 													  |
\*-----------------------------------------------------------------------*/

#include "demo.h"
#include "resource.h"

void InitPrgList(HWND hDlg);		// Fill program list
void InitTableList(HWND hDlg);
void InitControls(HWND hDlg);    // If program is selected init control list
void InitColumns(HWND hDlg);
void FreeApiStructs();
void SetReturnColumn(HWND hDlg); // initlalize global var return_column_num 

BOOL call_apg_lov(HWND hDlg);    // validate user input and call apg_lov

PTProgram		pPrgRepo ; 
PTTable			pTableRepo;
PTTaskVariable var_list;

int				return_column_num = 0; // Selected value is returned 
												  // from this column of table.
int				tot_cols = 0;			  // Selected Columns
int				*cols = NULL,			  // Selected Columns list of table
					*temp;


// Dialog Box callback function implementation

LRESULT CALLBACK DemoDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
		case WM_INITDIALOG:
				InitPrgList(hDlg);
				InitTableList(hDlg);
				return TRUE;

		case WM_COMMAND:
			switch (LOWORD(wParam))
			{
			case IDOK:
				if(!call_apg_lov(hDlg))
				{
					APIFree(cols);
					return TRUE;
				}
				// else close dialog 
				APIFree(cols);
				MessageBox( hDlg,"Congratulations !!!\nYou have successfully created"
					"\nList Of Values." ,szAppTitle, MB_OK);
			case IDCANCEL:
				{
					FreeApiStructs();
					EndDialog(hDlg, LOWORD(wParam));
					return TRUE;
				}
			case IDC_BUTTON_RET_COL:
					SetReturnColumn(hDlg);
					return TRUE;
			case IDC_COMBO_TABLES:
				switch (HIWORD(wParam)) 
					{ 
					case LBN_SELCHANGE: 
						InitColumns(hDlg);
						return TRUE; 
					} 
			case IDC_COMBO_PROGRAMS:
				switch (HIWORD(wParam)) 
					{ 
					case LBN_SELCHANGE: 
						InitControls(hDlg);
						return TRUE; 
					} 
			}
	}
	return FALSE;
}


// Check All Values and call apg_lov()

BOOL call_apg_lov(HWND hDlg)
{
	int  prg,		// Program to process
		  table, 	// Table for list of values.
		  col_num;	// Total selected columns in table
	char attachToCtrl[2]; // Parent task's control variable
	int SelectedVar = 0;  // Selected variable from controls variable list.
	BOOL ret_col_selected = FALSE; // Flag to check return column from lov to main prg.

	prg = SendDlgItemMessage(hDlg,IDC_COMBO_PROGRAMS, CB_GETCURSEL, 0,0) + 1;	
	if(prg <= 0 )
	{
		MessageBox(hDlg, "Please Select Program or table",szAppTitle,MB_OK);
		return FALSE;
	}
	table = SendDlgItemMessage(hDlg,IDC_COMBO_TABLES, CB_GETCURSEL, 0,0) + 1;	

	if(table <= 0)
	{
		MessageBox(hDlg, "Please Select Program or table",szAppTitle,MB_OK);
		return FALSE;
	}

	col_num = SendDlgItemMessage(hDlg,IDC_LIST_COLUMNS, LB_GETSELCOUNT , 0,0);
	if(col_num <= 0)
	{
		MessageBox(hDlg, "Please Select Columns",szAppTitle,MB_OK);
		return FALSE;
	}

	temp = cols = (int *)APIMalloc(sizeof(int)*(col_num+1));

	for( int i = 0; i< tot_cols; i++)
		if(SendDlgItemMessage(hDlg,IDC_LIST_COLUMNS, LB_GETSEL ,i,0) > 0)
		{
			*(++temp) = i+1;
			if( *temp == return_column_num ) 
			{
				// Adjust return_column_num in selection list.
				return_column_num = temp - cols;
				ret_col_selected = TRUE;
			}
		}
	if(!ret_col_selected) 
	{
		MessageBox(hDlg, "Please select Return Column properly",
			szAppTitle,MB_OK);
		return FALSE;
	}


	SelectedVar = SendDlgItemMessage(hDlg,IDC_LIST_FORM_CTRL, LB_GETCURSEL ,0,0) + 1;
	if(SelectedVar <= 0)
	{
		MessageBox(hDlg, "Please Select Control to attach pick List",szAppTitle,MB_OK);
		return FALSE;
	}

	memcpy(attachToCtrl, var_list[SelectedVar].variable, 2);

	// Call for generate list of values ( lov )
	apg_lov(prg,table,cols,col_num,attachToCtrl);

	return TRUE;
}

void SetReturnColumn(HWND hDlg)
{
	char szColumn[40];

	for( int i = 0; i< tot_cols; i++)
		if(SendDlgItemMessage(hDlg,IDC_LIST_COLUMNS, LB_GETSEL ,i,0) > 0)
			break;
	if( tot_cols == i ) // No column is selected.
		return;

	SendDlgItemMessage(hDlg,IDC_LIST_COLUMNS, LB_GETTEXT ,i,(LPARAM)&szColumn);

	SetWindowText( GetDlgItem(hDlg, IDC_EDIT_RETURN_COL), szColumn);
	
	return_column_num = ++i;
}


void InitPrgList(HWND hDlg)
{
	int prg_no ;
	if(APIErrCode = GetProgramRepository( &pPrgRepo))
		DisplayError(APIErrCode);
	for ( prg_no = 1 ; prg_no <= ApplicationData->programs ; prg_no++ )
	{
		char prg_name[100];
		sprintf(prg_name,"%3d. %s",prg_no,pPrgRepo[prg_no].name);
		SendDlgItemMessage(hDlg,IDC_COMBO_PROGRAMS, CB_ADDSTRING, 0, (LPARAM)prg_name);
	}
	if(prg_no > 1)
	{
		SendDlgItemMessage(hDlg,IDC_COMBO_PROGRAMS, CB_SETCURSEL, 0, 0);   // Select First Program
		InitControls(hDlg);
	}
	else
		MessageBox(hDlg, "There should be a program to generate List Of Values\n"
		"Please Create a program and then execute MgApi demo application",szAppTitle,MB_OK);

}

void InitTableList(HWND hDlg)
{
	int table_no ;
	if(APIErrCode = GetTableRepository( &pTableRepo))
		DisplayError(APIErrCode);

	for ( table_no = 1 ; table_no <= ApplicationData->tables ; table_no++ )
	{
		char table_name[100];
		sprintf(table_name,"%3d. %s",table_no,pTableRepo[table_no].name);
		SendDlgItemMessage(hDlg,IDC_COMBO_TABLES, CB_ADDSTRING, 0, (LPARAM) pTableRepo[table_no].name);
	}

	if(table_no > 1)
	{
		SendDlgItemMessage(hDlg,IDC_COMBO_TABLES, CB_SETCURSEL, 0, 0);  // Select First Table
		InitColumns(hDlg);
	}
	else
		MessageBox(hDlg, "There should be a table to generate List Of Values\n"
		"Please Create tables and then execute MgApi demo application",szAppTitle,MB_OK);
}

void InitColumns(HWND hDlg)
{
	HWND hwndList;
	int nItem, col_no;
	PTColumn pColumns;
	//
	// Delete All Previous columns if any.
	//
	SendDlgItemMessage(hDlg,IDC_LIST_COLUMNS, LB_RESETCONTENT , 0, 0);

	// Insert Table Column Names in List
	hwndList = GetDlgItem(hDlg, IDC_COMBO_TABLES); 
	nItem = SendMessage(hwndList, CB_GETCURSEL, 0, 0); 

	if(nItem == CB_ERR )
	return;

	if(APIErrCode = OpenTable(nItem+1))
	{
		DisplayError(APIErrCode);
		return;  // Can't continue
	}

	if(APIErrCode = GetTableColumns(&pColumns))
		DisplayError(APIErrCode);

	CloseTable();

	tot_cols = pTableRepo[nItem+1].columns;

	for ( col_no = 1 ; col_no <=	tot_cols; col_no++ )
	{
		SendDlgItemMessage(hDlg,IDC_LIST_COLUMNS, LB_ADDSTRING, 0, (LPARAM) pColumns[col_no].name);
	}
	
	FreeTableColumns( pColumns, tot_cols); 						
}

void InitControls(HWND hDlg)
{
	int  nItem, 
		  control_no;
	char str[80],
		  *variable_name;
	int  vars_no = 0;

	PTTaskForm pForm;
	PTFormControl pControls;
	PTTaskInfo pTaskInfo;

	//
	// Delete All Previous controls if any.
	//
	SendDlgItemMessage(hDlg,IDC_LIST_FORM_CTRL, LB_RESETCONTENT , 0, 0);

	// Insert Form Controls in List

	nItem = SendDlgItemMessage(hDlg,IDC_COMBO_PROGRAMS, CB_GETCURSEL, 0, 0); 

	if(nItem == CB_ERR )
		return;

	if(APIErrCode = OpenTask(nItem+1))
	{
		DisplayError(APIErrCode);
		return; // Can't continue
	}
	
	if(APIErrCode = GetFormControls(1,&pControls))
		DisplayError(APIErrCode);

	GetTaskInformation( &pTaskInfo);

	GetTaskForms(&pForm);
	
	vars_no = 0;
	if( var_list)
		APIFree(var_list);

	// Get List of used task variables.
	// to enable zoom action on control 
	// we have to add "call operation" after controls "select operation"

	var_list =(PTTaskVariable) APIMalloc( sizeof(TTaskVariable) * (pForm[1].form_controls+1));
	for ( control_no = 1 ; control_no <=  pForm[1].form_controls ; control_no++ )
	{
		// Check Control has data field and add data to controls list.
		if( pControls[control_no].data[0] != '?' && pControls[control_no].data[0] >= 'A')
		{
			ExpandVariableName (pControls[control_no].data, &variable_name);
			sprintf( str, "%ld , %2s , %s" ,   pControls[control_no].isn,
				pControls[control_no].data, variable_name ? variable_name : " " );
			SendDlgItemMessage(hDlg,IDC_LIST_FORM_CTRL, LB_ADDSTRING, 0, (LPARAM)str);
			// Fill task variable list
			memcpy(&var_list[++vars_no].variable,pControls[control_no].data,2);
			FreeVariableName(variable_name);
		}
	}

	// Select First control 
	if(vars_no > 1)
		SendDlgItemMessage(hDlg,IDC_LIST_FORM_CTRL, LB_SETCURSEL, 0, 0);
	
	// Release memory allocated in api
	// Fix - QCR # 926932
	FreeFormControls(pForm[1].interface_type, pControls, pForm[1].form_controls);
   FreeTaskForms(pForm,pTaskInfo->forms);
	FreeTaskInformation( pTaskInfo);
	CloseTask();
	return;
}

void	FreeApiStructs()
{
	FreeProgramRepository( pPrgRepo, ApplicationData->programs);
	FreeTableRepository( pTableRepo, ApplicationData->tables);
}
