// SelectdatasourcePage.cpp : implementation file
//

#include "stdafx.h"
#include "SelectdatasourcePage.h"
#include "ReportDict.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSelectdatasourcePage dialog

CSelectdatasourcePage::CSelectdatasourcePage(CaplReportMgr *ReportMgr, CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CSelectdatasourcePage::IDD, pParent)
{
	ASSERT(ReportMgr);
	m_ReportMgr = ReportMgr;
	//{{AFX_DATA_INIT(CSelectdatasourcePage)
	m_DSType = 0;
	m_sFileName = _T("");
	//}}AFX_DATA_INIT
	m_pSelectedHeader = NULL;
}


void CSelectdatasourcePage::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSelectdatasourcePage)
	DDX_Control(pDX, IDC_BROWSE_BTN, m_browsefile_btn);
	DDX_Control(pDX, IDC_QUERIES_LIST, m_QueryListCtrl);
	DDX_Radio(pDX, IDC_DS_FILE, m_DSType);
	DDX_Text(pDX, IDC_FILE_NAME, m_sFileName);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CSelectdatasourcePage, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CSelectdatasourcePage)
	ON_BN_CLICKED(IDC_DS_FILE, OnDsFile)
	ON_BN_CLICKED(IDC_DS_QUERY, OnDsQuery)
	ON_BN_CLICKED(IDC_BROWSE_BTN, OnBrowseBtn)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectdatasourcePage message handlers

void CSelectdatasourcePage::OnOK() 
{
	// TODO: Add extra validation here
	
//	CaplTranslateDialog::OnOK();
}

void CSelectdatasourcePage::OnCancel() 
{
	// TODO: Add extra cleanup here
	
//	CaplTranslateDialog::OnCancel();
}

BOOL CSelectdatasourcePage::OnInitDialog() 
{
	CaplTranslateDialog::OnInitDialog();

	m_browsefile_btn.EnableWindow(m_DSType==0?TRUE:FALSE);
	m_QueryListCtrl.EnableWindow(m_DSType==0?FALSE:TRUE);

	LoadAddins();

	int i, ind;
	CaplAddinElement* pElem;
	for(i=0; i<m_addin_elements.GetSize(); i++)
	{
		pElem = m_addin_elements[i];
		if(!pElem->m_query.m_descr.IsEmpty())
			ind = m_QueryListCtrl.AddString(pElem->m_query.m_descr);
		else
			ind = m_QueryListCtrl.AddString(pElem->m_query.m_function_name);
		m_QueryListCtrl.SetItemData(ind, (DWORD)pElem);
	}
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CSelectdatasourcePage::OnDsFile() 
{
	if(!UpdateData()) return;
	m_browsefile_btn.EnableWindow(m_DSType==0?TRUE:FALSE);
	m_QueryListCtrl.EnableWindow(m_DSType==0?FALSE:TRUE);
}

void CSelectdatasourcePage::OnDsQuery() 
{
	if(!UpdateData()) return;
	m_browsefile_btn.EnableWindow(m_DSType==0?TRUE:FALSE);
	m_QueryListCtrl.EnableWindow(m_DSType==0?FALSE:TRUE);
}

void CSelectdatasourcePage::LoadAddins()
{
	ResetAddins();
	CString sPath, sFile;
	CFileFind file_find;
	BOOL bContinue = TRUE;
	GetExePath(GetModuleHandle(NULL), sPath);
	if(file_find.FindFile(sPath+_T("*.dll")))
	{
		do 
		{
			if(!bContinue) break;
			bContinue = file_find.FindNextFile();
			sFile = file_find.GetFilePath();

			sFile.MakeLower();
			if(-1!=sFile.Find(_T("aplocicall.dll")))
				continue;
			if(-1!=sFile.Find(_T("aplocicalld.dll")))
				continue;

			HMODULE hMod = AfxLoadLibrary(sFile);
			if(hMod==0) continue;
			bool (*lpGetList)(CArray<CaplQuery, CaplQuery>*);
			(FARPROC&)lpGetList = GetProcAddress(hMod,"GetQueryList");
			if(lpGetList==0) 
			{
				AfxFreeLibrary(hMod);
				continue;
			}
			CArray<CaplQuery, CaplQuery> m_querys;
			if(!lpGetList(&m_querys))
			{
				AfxFreeLibrary(hMod);
				continue;
			}
			char*(*lpGetName)();
			(FARPROC&)lpGetName = GetProcAddress(hMod,"GetAddinName");
			CString name = sFile;
			if(lpGetName)
				name = lpGetName();
			for(int i=0; i<m_querys.GetSize();i++)
			{
				CaplAddinElement* elem = new CaplAddinElement;
				elem->m_query = m_querys.GetAt(i);
				elem->hMod = hMod;
				if(elem->m_query.m_function_name==_T("")) 
				{
					delete elem;
					continue;
				}
				(FARPROC&)elem->lpQueryFunc = GetProcAddress(hMod,(LPCSTR)CaplStringAdapter(elem->m_query.m_function_name));
				if(elem->lpQueryFunc==NULL) 
				{
					delete elem;
					continue;
				}
				m_addin_elements.Add(elem);
				elem->name = name;
			}
		}
		while(bContinue);
	}
}

void CSelectdatasourcePage::ResetAddins()
{
	int i;
	for(i=0; i<m_addin_elements.GetSize();i++)
	{
		AfxFreeLibrary(m_addin_elements.GetAt(i)->hMod);
		delete m_addin_elements.GetAt(i);
	}
	m_addin_elements.RemoveAll();
}

BOOL CSelectdatasourcePage::DestroyWindow() 
{
	ResetAddins();
	
	return CaplTranslateDialog::DestroyWindow();
}

CHeader* CSelectdatasourcePage::GetHeader()
{
	if(!TestUpdate()) return NULL;
	if(m_DSType==0)
	{
		CStdioFile f;
		if(!f.Open(m_sFileName,CFile::modeRead))
		{
			AfxMessageBox(_T("Не могу прочесть файл: ")+m_sFileName);
			return NULL;
		}
		m_pSelectedHeader = new CHeader(m_ReportMgr);
		CString str;
		if(f.ReadString(str))
		{
			if(str.CompareNoCase(_T("Data Source File"))==0)
			{
				do 
				{
					if(!f.ReadString(str))
						break;
				} while(str.CompareNoCase(_T("[Data]"))!=0);
				if(!f.ReadString(str))
				{
					AfxMessageBox(_T("Файл пуст!"));
					f.Close();
					delete m_pSelectedHeader;
					m_pSelectedHeader = NULL;
					return NULL;
				}
			}
			int ind = str.Find(_T(","));
			CString column;
			CHeaderColumn* val;
			while(ind>-1)
			{
				column = str.Left(ind);
				str = str.Right(str.GetLength()-ind-1);
				ind = str.Find(_T(","));
				column.TrimLeft(_T("\""));
				column.TrimRight(_T("\""));
				val = new CHeaderColumn(m_ReportMgr);
				val->m_name = column;
				val->m_type = aplSTRING;
				m_pSelectedHeader->AddColumn(val);
			}
			val = new CHeaderColumn(m_ReportMgr);
			val->m_type = aplSTRING;
			str.TrimLeft(_T("\""));
			str.TrimRight(_T("\""));
			val->m_name = str;
			m_pSelectedHeader->AddColumn(val);
		}
		else
		{
			AfxMessageBox(_T("Файл пуст!"));
			delete m_pSelectedHeader;
			m_pSelectedHeader = NULL;
			return NULL;
		}
		f.Close();
	}
	else
	{
		int cur = m_QueryListCtrl.GetCurSel();
		if(cur<0) return NULL;
		CaplAddinElement* pElem = (CaplAddinElement*)m_QueryListCtrl.GetItemData(cur);
		if(pElem==NULL) return NULL;
		CRParamsArray params;
		pElem->m_query.m_header = new CHeader(m_ReportMgr);
		pElem->lpQueryFunc(&pElem->m_query, params, APL_GET_HEADER);
		m_pSelectedHeader = pElem->m_query.m_header;
		pElem->m_query.m_header = NULL;
	}
	return m_pSelectedHeader;
}

bool CSelectdatasourcePage::TestUpdate()
{
	if(!UpdateData()) return false;
	if(m_DSType==0)
	{
		if(m_sFileName.IsEmpty()) 
		{
			AfxMessageBox(_T("Необходимо указать файл источника данных!"), MB_ICONINFORMATION|MB_OK);
			return false;
		}

		CStdioFile f;
		if(!f.Open(m_sFileName,CFile::modeRead))
		{
			AfxMessageBox(_T("Не могу прочесть файл: ")+m_sFileName);
			return false;
		}
		f.Close();
	}
	else
	{
		int cur = m_QueryListCtrl.GetCurSel();
		if(cur<0)
		{
			AfxMessageBox(_T("Необходимо указать источник данных!"), MB_ICONINFORMATION|MB_OK);
			return false;
		}
	}
	return true;
}

void CSelectdatasourcePage::OnBrowseBtn() 
{
	UpdateData();
	CFileDialog dlg(TRUE,_T("csv"),m_sFileName,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
		_T("Источник данных|*.csv;*.aplDSF|Файлы источника данных (*.aplDSF)|*.aplDSF|Файлы csv (*.csv)|*csv|Все файлы (*.*)|*.*|"));
	if(dlg.DoModal()==IDOK)
	{
		m_sFileName = dlg.GetPathName();
		
		UpdateData(FALSE);
	}
}
