// AddInSetupDlg.cpp : implementation file
//

#include "stdafx.h"
#include "AddInSetupDlg.h"
#include <afxtempl.h>
#include "afxdlgs.h"
#include "AddInModProp.h"
#include "FindPSSPluginsDlg.h"
#include "PSMDoc.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAddInSetupDlg dialog
#define MAX_FUCTION 10000
#define NON_PSM_ADDIN_MODULE  APL_T("Данная библиотека не является дополнением к PSM")

CAddInSetupDlg::CAddInSetupDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CAddInSetupDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAddInSetupDlg)
	m_view_descr = _T("");
	//}}AFX_DATA_INIT
	GetExePath(m_exe_path);
}


void CAddInSetupDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAddInSetupDlg)
	DDX_Control(pDX, IDC_VDESCR, m_view_descr_ctrl);
	DDX_Control(pDX, IDC_VIEW_LIST, m_view_list);
	DDX_Control(pDX, IDC_ADDIN_TAB, m_Tab_ctrl);
	DDX_Control(pDX, IDC_ADDIN_PROP, m_properties);
	DDX_Control(pDX, IDC_DELETE, m_del_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_FDESCR, m_ctrlFDescr);
	DDX_Control(pDX, IDC_DESCR, m_ctrlDescr);
	DDX_Control(pDX, IDC_ENABLE, m_ctrlEnDis);
	DDX_Control(pDX, IDC_PLUGIN_LIST, m_ctrlPList);
	DDX_Control(pDX, IDC_FUNCTION_LIST, m_ctrlFList);
	DDX_Text(pDX, IDC_VDESCR, m_view_descr);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CAddInSetupDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CAddInSetupDlg)
	ON_BN_CLICKED(ID_ADD_PLUGIN, OnAddPlugin)
	ON_LBN_SELCHANGE(IDC_PLUGIN_LIST, OnSelchangePluginList)
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	ON_LBN_SELCHANGE(IDC_FUNCTION_LIST, OnSelchangeFunctionList)
	ON_BN_CLICKED(IDC_DISABLE, OnDisable)
	ON_BN_CLICKED(IDC_ENABLE, OnEnable)
	ON_BN_CLICKED(IDC_ADDIN_PROP, OnAddinProp)
	ON_LBN_SELCHANGE(IDC_VIEW_LIST, OnSelchangeViewList)
	ON_NOTIFY(TCN_SELCHANGE, IDC_ADDIN_TAB, OnSelchangeAddinTab)
	ON_BN_CLICKED(ID_FIND_PLUGINS, OnFindPlugins)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_PLUGIN_LIST, OnItemchangedPluginList)
	ON_NOTIFY(NM_CLICK, IDC_PLUGIN_LIST, OnClickPluginList)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAddInSetupDlg message handlers

BOOL CAddInSetupDlg::OnInitDialog() 
{
	CaplResizableDialog::OnInitDialog();

	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   

	AddAnchor(ID_ADD_PLUGIN,TOP_RIGHT);
	AddAnchor(IDC_PLUGIN_LIST,TOP_LEFT,TOP_RIGHT);
	AddAnchor(IDC_FUNCTION_LIST,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_DESCR,TOP_LEFT,TOP_RIGHT);
	AddAnchor(IDC_ADDIN_PROP,TOP_RIGHT);
	AddAnchor(IDC_DELETE,TOP_RIGHT);
	AddAnchor(IDC_ENABLE,TOP_RIGHT);
	AddAnchor(IDC_DISABLE,TOP_RIGHT);
	AddAnchor(ID_FIND_PLUGINS,TOP_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_FDESCR,BOTTOM_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_ADDIN_TAB,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_VDESCR,BOTTOM_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_VIEW_LIST,TOP_LEFT,BOTTOM_RIGHT);

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);

	m_Tab_ctrl.InsertItem(0, APL_T("Список функций"));
	m_Tab_ctrl.InsertItem(1, APL_T("Список закладок"));
	m_view_list.ShowWindow(SW_HIDE);
	m_view_descr_ctrl.ShowWindow(SW_HIDE);

	m_show_all = false;
	CenterWindow();
	CRect rect;
	m_ctrlPList.GetWindowRect(&rect);
	m_ctrlPList.InsertColumn(0, APL_T("Имя файла"),LVCFMT_LEFT,rect.Width()*6/20);
	m_ctrlPList.InsertColumn(1, APL_T("Название дополнения"),LVCFMT_LEFT,rect.Width()*12/20);
	m_ctrlPList.InsertColumn(2, APL_T("Полный путь к дополнению"),LVCFMT_LEFT,rect.Width()*8/10);

//D	m_ctrlPList.AddString("*** Функции всех дополнений ***");
	m_ctrlPList.InsertItem(0,_T("***"));
	m_ctrlPList.SetItemText(0,1, APL_T("*** Функции всех дополнений ***"));
	m_ctrlPList.SetItemData(0,0);
	LoadPlugins();
//D	m_ctrlPList.SetCurSel(0);
//	m_ctrlPList.SetSelectionMark(0);
	m_ctrlPList.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);
	m_ctrlPList.ModifyStyle(0, LVS_SHOWSELALWAYS);
	m_ctrlPList.SetItemState(0, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);

	m_del_btn.EnableWindow(FALSE);
	m_properties.EnableWindow(FALSE);
	OnShowAll();
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

bool CAddInSetupDlg::LoadPlugins()
{
	m_view_list.ResetContent();
	m_ctrlFList.ResetContent();
	m_view_descr = _T("");
	m_ctrlDescr.SetWindowText(_T(""));
	m_ctrlFDescr.SetWindowText(_T(""));
	UpdateData(FALSE);
	
	CaplStringFile pl_file;
	CString err_mess(_T(""));
	CString sPath(_T(""));//костыли
	m_views.DeleteAllViews();

	if(!pl_file.Open(m_exe_path+_T("psm.add"),CFile::modeRead|CFile::shareDenyNone))
	{
		return false;
	}

	for(int fi=0; fi<1;)
	{
		CaplPluginItem *pItem = new CaplPluginItem;
		ASSERT(pItem);
		pItem->m_bShowWarningMessage = false;
		int res = pItem->ReadDataFromFile(pl_file, sPath, APL_LOAD_INFO,&err_mess);
		if(res==0)//Фсё норм
		{
			pItem->m_index = 0;
		}
		else if(res==-3)//Файл не найден
		{
			pItem->m_index = -2;
		}
		else if(res==-4)
		{
			pItem->m_index = -1;
		}
		else
		{
			delete pItem;
			if(res==-2 || res==-1) 
				break;
		}

//D		int ind = m_ctrlPList.AddString(pItem->m_sName);
		CString only_name=GetOnlyFileName(pItem->m_sPath);
		int ind = m_ctrlPList.InsertItem(m_ctrlPList.GetItemCount(),only_name);
		m_ctrlPList.SetItemText(ind,1,pItem->m_sName);
		m_ctrlPList.SetItemData(ind, (DWORD)pItem);
		if(pItem->m_sPath!=only_name){
			m_ctrlPList.SetItemText(ind,2,pItem->m_sPath);
		}else{
			m_ctrlPList.SetItemText(ind,2,m_exe_path+pItem->m_sPath);
		}
	}
	pl_file.Close();
	if(err_mess!=_T("")){
		AfxMessageBox( APL_T("При загрузке дополнений возникли следующие ошибки:")+err_mess,MB_SYSTEMMODAL|MB_OK);
	}

	return true;
}

void CAddInSetupDlg::OnAddPlugin() 
{
	CFileDialog f_dlg(true,_T("*.dll"),_T("*.dll"),OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT | OFN_EXPLORER | OFN_FILEMUSTEXIST,
		 APL_T("Файлы библиотек (*.dll)|*.dll|Все файлы (*.*)|*.*|"),this);
	if(f_dlg.DoModal()==IDOK)
	{
		POSITION pos = f_dlg.GetStartPosition();
		while(pos!=NULL)
		{
			CString full_path = f_dlg.GetNextPathName(pos);
			CString file_name=GetOnlyFileName(full_path);
			if(FindAddin(file_name))
			{
				AfxMessageBox( APL_T("Дополнение с таким именем уже подключено."));
				return;
			}
			HMODULE hModule = AfxLoadLibrary(full_path);
			if(hModule)
			{
				CaplPluginItem *pItem (NULL); 
				int ind;
				LPFUNCTION lpFunc;
				
				bool (*lpGetFunctList)(CArray<CaplItemInfo*,CaplItemInfo*>*);
				(FARPROC&)lpGetFunctList = GetProcAddress(hModule,"GetFunctionsList"); //-V614
				if(lpGetFunctList)
				{
					pItem= new CaplPluginItem;
					pItem->m_sPath = full_path;

					CArray<CaplItemInfo*,CaplItemInfo*> funtions;
					lpGetFunctList(&funtions);
					for(int f=0; f<funtions.GetSize();f++)
					{
						CaplItemInfo *item = funtions.GetAt(f);

						CaplPluginItem::FunctionInfo* func_info= new CaplPluginItem::FunctionInfo;
						func_info->sFunction= item->m_menuName;
						func_info->flag= 1;
						func_info->sType= item->m_treeItemType;
						if(!(0==item->m_image || -1==item->m_image))
						{
							func_info->ico=LoadIcon(hModule,MAKEINTRESOURCE(item->m_image));
						}
						func_info->sDescr= item->m_description;
						
						if(!item->m_functionName.IsEmpty())
						{
#ifdef _UNICODE
							CaplStringAdapter sFunctionName(item->m_functionName);
							(FARPROC&)lpFunc = GetProcAddress(hModule,(LPCSTR)sFunctionName);
#else
							(FARPROC&)lpFunc = GetProcAddress(hModule,item->m_functionName);
#endif
						}
						else
							lpFunc = NULL;
						func_info->lpFunction=lpFunc;

						pItem->m_Functions.Add(func_info);
					}
				}
				else
				{
//					AfxMessageBox(NON_PSM_ADDIN_MODULE);
					AfxFreeLibrary(hModule);
					continue;
				}
				ind = m_ctrlPList.InsertItem(m_ctrlPList.GetItemCount(),file_name);
				
				char *(*lpGetAddInName)();
				(FARPROC&)lpGetAddInName = GetProcAddress(hModule,"GetAddInName"); //-V614
				if(lpGetAddInName!=NULL)
				{
					CString p_name = lpGetAddInName();
					pItem->m_sName = p_name;					
//D					if(p_name==_T("")) p_name = filename;
//D					else p_name += _T(" (")+filename+_T(")");
//D					ind = m_ctrlPList.AddString(p_name);
				}
				else
				{
//					pItem->m_sName = file_name;
//D					ind = m_ctrlPList.AddString(name);
				}
				(FARPROC&)lpGetAddInName = GetProcAddress(hModule,"GetAddInDescription");
				if(lpGetAddInName)
					pItem->m_sDescr =lpGetAddInName();
				bool (*lpGetViews)(CaplAddinViews*);
				(FARPROC&)lpGetViews = GetProcAddress(hModule,"GetTabViews"); //-V614
				if(lpGetViews!=0)
					lpGetViews(pItem->m_local_views);
				
				m_ctrlPList.SetItemText(ind,1,pItem->m_sName);
				m_ctrlPList.SetItemData(ind,(DWORD)pItem);
				if(pItem->m_sPath!=file_name){
					m_ctrlPList.SetItemText(ind,2,pItem->m_sPath);
				}else{
					m_ctrlPList.SetItemText(ind,2,m_exe_path+pItem->m_sPath);
				}
				
			}
			else
			{
				CString str=_T("");
				str.Format(_T("%d"),::GetLastError());
				AfxMessageBox( APL_T("Ошибка чтения библиотеки - ")+str);			
			}
		}
//D		int cur = m_ctrlPList.GetCurSel();
		int cur = m_ctrlPList.GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
		if(cur==0) OnShowAll();
	}
}

CString CAddInSetupDlg::GetMenuPath(CString menu)
{
	int ind=0;
	while((ind=menu.Find(_T('['),0))>-1)
	{
		int ind2 = menu.Find(_T(']'),ind);
		menu.Delete(ind,ind2-ind+1);
	}
	ind = menu.ReverseFind(_T('\\'));
	if(ind==menu.GetLength()-1)
		menu+= APL_T("<Разделитель>");
	return menu;
}


void CAddInSetupDlg::OnDelete() 
{
//D	int ind = m_ctrlPList.GetCurSel();
	int ind = m_ctrlPList.GetNextItem( -1 , LVNI_SELECTED );
	if(ind<1) return;
	if(MessageBox( APL_T("Вы действительно желаете удалить модуль дополнения?"), APL_T("Удаление"),MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2)==IDNO) return;

	CaplPluginItem *pItem;
	ind = -1;
	while((ind=m_ctrlPList.GetNextItem(ind, LVNI_SELECTED))>-1)
	{
		pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(ind);
		if(pItem)
			delete pItem;
		m_ctrlPList.DeleteItem(ind--);
	}
	OnSelchangePluginList();
}

void CAddInSetupDlg::OnSelchangeFunctionList() 
{
	if(!m_show_all)
	{
//D		int p_ind = m_ctrlPList.GetCurSel();
		int p_ind = m_ctrlPList.GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
		if(p_ind<0)
		{
			m_ctrlFDescr.SetWindowText(_T(""));
			return;
		}
		int ind	= m_ctrlFList.GetCurSel();
		if(ind<0)
		{
			m_ctrlFDescr.SetWindowText(_T(""));
			return;
		}
		CaplPluginItem* pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(p_ind);
		if(pItem)
		{
			pItem->m_Functions[ind]->flag= m_ctrlFList.GetCheck(ind);
			m_ctrlFDescr.SetWindowText(pItem->m_Functions[ind]->sDescr);
		}
	}
	else
	{
		int ind	= m_ctrlFList.GetCurSel();
		if(ind<0) 
		{
			m_ctrlFDescr.SetWindowText(_T(""));
			return;
		}
		int plug = m_ctrlFList.GetItemData(ind);
		int f = plug/MAX_FUCTION;
		plug = plug - f*MAX_FUCTION;
		CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(plug);
		if(pItem)
		{
			pItem->m_Functions[f]->flag= m_ctrlFList.GetCheck(ind);
			m_ctrlFDescr.SetWindowText(pItem->m_Functions[f]->sDescr);
		}
	}
}


void CAddInSetupDlg::OnDisable() 
{
//D	int ind = m_ctrlPList.GetCurSel();
	int ind = m_ctrlPList.GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
	if(ind<0) return;
	CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(ind);
	if(pItem>0)
	{
		for(int i=0; i<pItem->m_Functions.GetSize();i++)
		{
			pItem->m_Functions[i]->flag= 0;
			m_ctrlFList.SetCheck(i, FALSE);
		}
	}
	else
	{
//D		int pcount = m_ctrlPList.GetCount();
		int pcount = m_ctrlPList.GetItemCount();
		int ind = 0;
		for(int p=1; p<pcount;p++)
		{
			CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(p);
			if(pItem)
			for(int f=0; f<pItem->m_Functions.GetSize();f++)
			{
				pItem->m_Functions[f]->flag= 0;
				m_ctrlFList.SetCheck(f, FALSE);

				ind++;
			}
		}
	}
}

void CAddInSetupDlg::OnEnable() 
{
//D	int ind = m_ctrlPList.GetCurSel();
	int ind = m_ctrlPList.GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
	if(ind<0) return;
	CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(ind);
	if(pItem>00)
		
		for(int i=0; i<pItem->m_Functions.GetSize();i++)
		{
			pItem->m_Functions[i]->flag= 1;
			m_ctrlFList.SetCheck(i, TRUE);
		}
	else
	{
//D		int pcount = m_ctrlPList.GetCount();
		int pcount = m_ctrlPList.GetItemCount();
		int ind = 0;
		for(int p=1; p<pcount;p++)
		{
			CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(p);
			if(pItem)
			for(int f=0; f<pItem->m_Functions.GetSize();f++)
			{
				pItem->m_Functions[f]->flag= 1;
				m_ctrlFList.SetCheck(ind, TRUE);
				ind++;
			}
		}
	}
}

void CAddInSetupDlg::OnShowAll() 
{
	m_ctrlFList.ResetContent();
	m_view_list.ResetContent();
//D	int pcount = m_ctrlPList.GetCount();
	int pcount = m_ctrlPList.GetItemCount();
	CString func;
	for(int p=1; p<pcount;p++)
	{
		CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(p);
		if(pItem)
		for(int f=0; f<pItem->m_Functions.GetSize();f++)
		{
			func = pItem->m_Functions[f]->sType;
			func=ReplaceType(func)+_T(": ")+GetMenuPath(pItem->m_Functions[f]->sFunction);
			int ind = m_ctrlFList.AddString(func);
			m_ctrlFList.SetCheck(ind,pItem->m_Functions[f]->flag);
			m_ctrlFList.SetItemData(ind,p+f*MAX_FUCTION);
		}

		if(pItem->m_local_views)
		{
			for(int i=0; i<pItem->m_local_views->GetSize();i++)
			{
				CaplViewInfo *vi = pItem->m_local_views->GetAt(i);
				int ind = m_view_list.AddString(GetTypeName(vi->type)+_T(" ")+vi->tab_name);
				m_view_list.SetItemData(ind,(DWORD)vi);
				m_view_list.SetCheck(ind, vi->show);
			}
		}
	}
	m_show_all = true;
}

void CAddInSetupDlg::OnCancel() 
{
//D	WORD count = m_ctrlPList.GetCount();
	WORD count = m_ctrlPList.GetItemCount();
	CaplStringFile f;
// 	if(!f.Open(m_exe_path+_T("psm.add"),CFile::modeReadWrite))
	if(!f.Open(m_exe_path+_T("psm.add"),CFile::modeCreate | CFile::modeReadWrite)) 
	{
		AfxMessageBox( APL_T("Не могу создать файл ")+m_exe_path+_T("psm.add"));
		CaplResizableDialog::OnCancel();
		return;
	}
	for(int i=0; i<count; i++)
	{
		CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(i);
		if(pItem)
		{
			pItem->WriteDataToFile(f);
			pItem->FreeItem();
			delete pItem;
		}
	}
	f.Close();
	
	CaplResizableDialog::OnCancel();
}

CString CAddInSetupDlg::ReplaceType(CString tname)
{
	if(tname==_T("")) tname =  APL_T("Главное меню");
	else if(tname==APL_TREE_ITEM_FOLDER) tname =  APL_T("Папка");
	else if(tname==APL_TREE_ITEM_CATEGORIES) tname =  APL_T("Категория");
	else if(tname==APL_TREE_ITEM_PRODUCT) tname =  APL_T("Изделие");
	else if(tname==APL_TREE_ITEM_DOCUMENT) tname =  APL_T("Документ");
	else if(tname==APL_TREE_ITEM_LOT) tname =  APL_T("Партия изделий");
	else if(tname==APL_TREE_ITEM_PRDINST) tname =  APL_T("Экземпляр изделия");
	else if(tname==APL_TREE_ITEM_REFUSAL) tname =  APL_T("Неисправность");
	else if(tname==APL_TREE_ITEM_CHARACTERISTIC) tname =  APL_T("Характеристика");
	else if(tname==APL_TREE_ITEM_BP) tname =  APL_T("Бизнес-процесс");
	else if(tname==APL_TREE_ITEM_BPINST) tname =  APL_T("Экземпляр бизнес-процесса");
	else if(tname==APL_TREE_ITEM_BPRES) tname =  APL_T("Ресурс бизнес-процесса");
	else if(tname==APL_TREE_ITEM_APPROVAL) tname =  APL_T("Электронная подпись");
	else if(tname==APL_TREE_ITEM_PROJECT) tname =  APL_T("Проект");
	else if(tname==APL_TREE_ITEM_ACTIVITY) tname=  APL_T("Действие");
	else if(tname==APL_TREE_ITEM_TASK) tname=  APL_T("Задание");
	else if(tname==APL_TREE_ITEM_PROCESSTMPL) tname=  APL_T("Шаблон");
	else if(tname==APL_TREE_ITEM_PROCESS) tname=  APL_T("Процесс");
	else if(tname==APL_TREE_ITEM_QUERY) tname=  APL_T("Поиск в БД");
	else if(tname==APL_TREE_ITEM_FIND) tname=  APL_T("Быстрый поиск в БД");
	else if(tname==APL_TREE_ITEM_QUERY_NIIAO) tname=  APL_T("Комбинированный поиск");
	else if(tname==APL_TREE_ITEM_COMBINED_TABLE) tname=  APL_T("Сводная таблица");
	else if(tname==APL_TREE_ITEM_CLASSIFIERLEVEL) tname=  APL_T("Уровень структуры справочника");
	else if(tname==APL_TREE_ITEM_CLASSIFIERSYSTEM) tname=  APL_T("Справочник");

	return tname;
}

bool CAddInSetupDlg::FindAddin(CString path)
{
//D	int cnt = m_ctrlPList.GetCount();	
	int cnt = m_ctrlPList.GetItemCount();
	CString sFileName, sPlIFileName;
	int iIndex= -1;

//	iIndex= path.ReverseFind(_T('\\'));
//	if(-1!=iIndex) sFileName= path.Right(path.GetLength()-1 - iIndex);
//	else sFileName= path;
	sFileName=GetOnlyFileName(path);

	for(int i=0; i<cnt; i++)
	{
		CaplPluginItem *item = (CaplPluginItem*)m_ctrlPList.GetItemData(i);
		if(item!=0)
		{
			CString tmp = item->m_sPath;
			
			iIndex= tmp.ReverseFind(_T('\\'));
			if(-1!=iIndex) sPlIFileName= tmp.Right(tmp.GetLength()-1 - iIndex);
			else sPlIFileName= tmp;
			
			if(!sFileName.CompareNoCase(sPlIFileName)) return true;
		}
	}
	return false;
}

void CAddInSetupDlg::OnAddinProp() 
{
//D	int ind = m_ctrlPList.GetCurSel();
	int ind = m_ctrlPList.GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
	if(ind<0) return;
	CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(ind);
	if(pItem<=0) return;
	CAddInModProp dlg;
	dlg.m_pItem = pItem;
	if(dlg.DoModal()==IDOK)
	{
		pItem->UpdateItem();
	}
}

void CAddInSetupDlg::OnSelchangeAddinTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	int cur = m_Tab_ctrl.GetCurSel();
	if(cur==0 && !m_ctrlFList.IsWindowVisible())
	{
		m_ctrlFList.ShowWindow(SW_SHOW);
		m_ctrlFDescr.ShowWindow(SW_SHOW);
		m_view_list.ShowWindow(SW_HIDE);
		m_view_descr_ctrl.ShowWindow(SW_HIDE);
	}
	else if(cur==1 && !m_view_list.IsWindowVisible())
	{
		m_view_list.ShowWindow(SW_SHOW);
		m_view_descr_ctrl.ShowWindow(SW_SHOW);
		m_ctrlFList.ShowWindow(SW_HIDE);
		m_ctrlFDescr.ShowWindow(SW_HIDE);
	}
	
	*pResult = 0;
}

CString CAddInSetupDlg::GetTypeName(UINT type)
{
	CString res=_T("");
	if(type&APL_PDF_ITEM) res+= APL_T("Версия изделия");
	if(type&APL_PRD_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Продукт");}
	if(type&APL_CHARACT_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Характеристика");}
	if(type&APL_FOLDER_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Папка");}
	if(type&APL_DOC_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Документ");}
	if(type&APL_DOC_REVISION_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Версия документа");}
	if(type&APL_CATEG_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Категория");}
	if(type&APL_CATEG_REVISION_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Версия категории");}
	if(type&APL_BP_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Бизнес процесс");}
	if(type&APL_BP_REVISION_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Версия бизнес процесса");}
	if(type&APL_ORG_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Организационная структура");}
	if(type&APL_PERSON_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Сотрудник");}
	if(type&APL_PRD_INST_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Экземпляр изделия");}
	if(type&APL_LOT_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Партия изделий");}
	if(type&APL_BP_INST_ITEM) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Экземпляр бизнес-процесса");}
	if(type&APL_PROJECT) {if(!res.IsEmpty()) res+=_T(" ");res+= APL_T("Проект");}
	return res;
}

void CAddInSetupDlg::OnFindPlugins() 
{
	CString buf;
	CFindPSSPluginsDlg dlg;
	for(int i=0; i<m_ctrlPList.GetItemCount(); i++)
	{
		CaplPluginItem* pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(i);
		if(pItem)
		{
			dlg.AddFileNameToSkip(GetOnlyFileName(pItem->m_sPath));
		}
	}
	if(dlg.DoModal()==IDOK)
	{
		int pos = dlg.GetFirstFileIndex();
		while(pos>-1)
		{
			CString file_name = dlg.GetNextFile(pos);
			CaplPluginItem *pItem = new CaplPluginItem;
			CString Name = pItem->Create(file_name);
			if(Name.IsEmpty())
				delete pItem;
			else
			{
				CString only_name=GetOnlyFileName(pItem->m_sPath);
				int ind = m_ctrlPList.InsertItem(m_ctrlPList.GetItemCount(),only_name);
				m_ctrlPList.SetItemText(ind,1,pItem->m_sName);
				m_ctrlPList.SetItemData(ind, (DWORD)pItem);
				if(pItem->m_sPath!=only_name){
					m_ctrlPList.SetItemText(ind,2,pItem->m_sPath);
				}else{
					m_ctrlPList.SetItemText(ind,2,m_exe_path+pItem->m_sPath);
				}
			}
		}
	}
}

void CAddInSetupDlg::OnSelchangeViewList() 
{
	UpdateData(TRUE);
	m_view_descr = _T("");
	int ind	= m_view_list.GetCurSel();
	if(ind>-1)
	{
		CaplViewInfo *vi = (CaplViewInfo*)m_view_list.GetItemData(ind);
		if(vi>0)
		{
			m_view_descr = vi->tab_descr;
			if(m_view_list.GetCheck(ind)>0)
				vi->show = true;
			else 
				vi->show = false;
		}
	}
	UpdateData(FALSE);
}


void CAddInSetupDlg::OnItemchangedPluginList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;
	// TODO: Add your control notification handler code here

	*pResult = 0;
}

void CAddInSetupDlg::OnSelchangePluginList() 
{
	m_ctrlFDescr.SetWindowText(_T(""));
	m_show_all = false;
	m_ctrlFList.ResetContent();
	m_view_list.ResetContent();
	//D	int ind = m_ctrlPList.GetCurSel();
	int ind = m_ctrlPList.GetNextItem( -1 , LVNI_ALL | LVNI_SELECTED );
	if(ind<0) return;
	if(ind==0)
	{
		m_ctrlDescr.SetWindowText( APL_T("Список всех функций, подключенных к системе"));
		m_del_btn.EnableWindow(FALSE);
		m_properties.EnableWindow(FALSE);
		OnShowAll();
		return;
	}
	else
	{
		m_del_btn.EnableWindow(TRUE);
		m_properties.EnableWindow(TRUE);
	}
	CaplPluginItem *pItem = (CaplPluginItem*)m_ctrlPList.GetItemData(ind);
	if(pItem==0)
		return;
	
	int count = pItem->m_Functions.GetSize();
	CString tname;
	int i;

	for(i=0; i<count; i++)
	{
		tname = pItem->m_Functions[i]->sType;
		int ind = m_ctrlFList.AddString(ReplaceType(tname)+_T(": \"")+GetMenuPath(pItem->m_Functions[i]->sFunction)+_T("\""));
		m_ctrlFList.SetCheck(ind,pItem->m_Functions[i]->flag);
	}
	if(pItem->m_local_views)
	{
		for(i=0; i<pItem->m_local_views->GetSize();i++)
		{
			CaplViewInfo *vi = pItem->m_local_views->GetAt(i);
			int ind = m_view_list.AddString(GetTypeName(vi->type)+_T(" ")+vi->tab_name);
			m_view_list.SetItemData(ind,(DWORD)vi);
			m_view_list.SetCheck(ind, vi->show);
		}
	}
	m_ctrlDescr.SetWindowText(pItem->m_sDescr);
}


void CAddInSetupDlg::OnClickPluginList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	
	*pResult = 0;
	OnSelchangePluginList();

}
