// SelectProcessTemplDlg.cpp : implementation file
//

#include "stdafx.h"
#include "aplWorkFlowManager.h"
#include "SelectProcessTemplDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CSelectProcessTemplDlg dialog

static CString m_sLastFilter;
static CString m_sLastFind;


CSelectProcessTemplDlg::CSelectProcessTemplDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CSelectProcessTemplDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSelectProcessTemplDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT

	m_api=0;
	m_wf_mgr=0;
	m_sel_template=0;
	m_sel_activity=0;
	m_bEditorMode=false;
	m_bShowAllTemplates = true;
	m_iEditorResultMode=0;
	m_SelectMode = APL_MODE_WFL_SELECT_TEMPLATE;
}


void CSelectProcessTemplDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSelectProcessTemplDlg)
	DDX_Control(pDX, IDC_DELETE, m_delete_btn);
	DDX_Control(pDX, IDC_CHANGE, m_change_btn);
	DDX_Control(pDX, IDC_CREATE_COPY, m_create_copy_btn);
	DDX_Control(pDX, IDC_CREATE_NEW, m_create_new_btn);
	DDX_Control(pDX, IDC_GRAPH, m_graph_ramka);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_FIND_EDIT, m_FindEdit);
	DDX_Control(pDX, IDC_FIND, m_FindBtn);
	DDX_Control(pDX, IDC_FIND_TOP, m_FindTopBtn);
	DDX_Control(pDX, IDC_FIND_BOTTOM, m_FindBottomBtn);
	DDX_Control(pDX, IDC_FILTR_EDIT, m_filtrEdit);
	DDX_Control(pDX, IDC_FILTR, m_FiltrBtn);
}


BEGIN_MESSAGE_MAP(CSelectProcessTemplDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CSelectProcessTemplDlg)
	ON_WM_CREATE()
	ON_BN_CLICKED(IDC_CREATE_NEW, OnCreateNew)
	ON_BN_CLICKED(IDC_CREATE_COPY, OnCreateCopy)
	ON_BN_CLICKED(IDC_CHANGE, OnChange)
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_FIND, &CSelectProcessTemplDlg::OnBnClickedFind)
	ON_BN_CLICKED(IDC_FIND_BOTTOM, &CSelectProcessTemplDlg::OnBnClickedFindBottom)
	ON_BN_CLICKED(IDC_FIND_TOP, &CSelectProcessTemplDlg::OnBnClickedFindTop)
	ON_BN_CLICKED(IDC_FILTR, &CSelectProcessTemplDlg::OnBnClickedFiltr)
	ON_WM_CLOSE()
	ON_WM_DESTROY()
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectProcessTemplDlg message handlers

int CSelectProcessTemplDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CaplResizableDialog::OnCreate(lpCreateStruct) == -1)
		return -1;

	
	RECT rect={0,0,10,10};
	//m_frame=(CaplWfTemplateFrame*)(RUNTIME_CLASS(CaplWfTemplateFrame)->CreateObject());
	m_frame=(CFrameWnd*)(RUNTIME_CLASS(CFrameWnd)->CreateObject());

	//m_frame->m_wf_mgr=m_wf_mgr;
	m_frame->Create(0,_T("aaa"),WS_CHILD|WS_VISIBLE,	rect,this);

	
	m_splitter.CreateStatic(m_frame,1,2);
	m_splitter.CreateView(0,0,RUNTIME_CLASS(CWfSelTemplatesTree), CSize(200,50),0);
	m_splitter.CreateView(0,1,RUNTIME_CLASS(CaplWfTemplateFrame), CSize(0,0),0);

	m_templates_tree=(CWfSelTemplatesTree*)(m_splitter.GetPane(0,0));
	m_templates_frame=(CaplWfTemplateFrame*)(m_splitter.GetPane(0,1));

	m_templates_tree->m_graph_view=m_templates_frame->m_view;

	return 0;
}


BOOL CSelectProcessTemplDlg::OnInitDialog() 
{
	CaplResizableDialog::OnInitDialog();
	
	RECT rect;
	m_graph_ramka.GetWindowRect(&rect);
	ScreenToClient(&rect);
	m_frame->MoveWindow(&rect,FALSE);

	AddAnchor(IDCANCEL, BOTTOM_RIGHT);
	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDC_DELETE, TOP_RIGHT);

	AddAnchor(IDC_ST_FIND, BOTTOM_LEFT);
	AddAnchor(IDC_FIND_EDIT, BOTTOM_LEFT);
	AddAnchor(IDC_FIND, BOTTOM_LEFT);
	AddAnchor(IDC_FIND_TOP, BOTTOM_LEFT);
	AddAnchor(IDC_FIND_BOTTOM, BOTTOM_LEFT);
	
	AddAnchor(IDC_ST_FILTER, BOTTOM_LEFT);
	AddAnchor(IDC_FILTR_EDIT, BOTTOM_LEFT);
	AddAnchor(IDC_FILTR, BOTTOM_LEFT);

	//m_frame->m_view->ZoomAllObj();

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

	m_change_btn.SetFlat(FALSE);
	m_create_copy_btn.SetFlat(FALSE);
	m_create_new_btn.SetFlat(FALSE);
	m_delete_btn.SetFlat(FALSE);


	m_FiltrBtn.SetFlat(FALSE);
	m_FindBtn.SetFlat(FALSE);
	m_FindTopBtn.SetFlat(FALSE);
	m_FindBottomBtn.SetFlat(FALSE);

	m_FiltrBtn.SetIcon(GetAplTableIco(APL_TABLE_FILTER)); m_FiltrBtn.SetWindowText(_T(""));
	m_FindBtn.SetIcon(GetAplTableIco(APL_TABLE_FIND)); m_FindBtn.SetWindowText(_T(""));
	m_FindTopBtn.SetIcon(GetAplStdIco16(APLSTDICO_TOP));m_FindTopBtn.SetWindowText(_T(""));
	m_FindBottomBtn.SetIcon(GetAplStdIco16(APLSTDICO_BOTTOM));m_FindBottomBtn.SetWindowText(_T(""));

	if(m_bEditorMode)
	{
		//m_ok_btn.ShowWindow(SW_HIDE);

		CBitmap bmp0;
		bmp0.LoadBitmap(IDB_TC_MGR_TEMPL);
		m_il.Create(16,16,ILC_COLOR24|ILC_MASK,0,10);
		m_il.Add(&bmp0,RGB(192,192,192));
		m_create_new_btn.SetIcon(m_il.ExtractIcon(0));
		m_create_copy_btn.SetIcon(m_il.ExtractIcon(1));
		m_change_btn.SetIcon(m_il.ExtractIcon(2));
		m_delete_btn.SetIcon(m_il.ExtractIcon(3));

		m_ok_btn.SetWindowText(APL_T("Изменить"));
		m_ok_btn.SetIcon(m_il.ExtractIcon(2));
	}
	else
	{
		m_change_btn.ShowWindow(SW_HIDE);
		m_create_copy_btn.ShowWindow(SW_HIDE);
		m_create_new_btn.ShowWindow(SW_HIDE);
		m_delete_btn.ShowWindow(SW_HIDE);

		RECT rect1;
		m_create_new_btn.GetWindowRect(&rect1);
		ScreenToClient(&rect1);
		rect.top=rect1.top;
		m_frame->MoveWindow(&rect,FALSE);
	}
	AddAnchor(m_frame->m_hWnd, TOP_LEFT, BOTTOM_RIGHT);
	m_templates_tree->m_bEditorMode=m_bEditorMode;
	
	m_templates_tree->m_api=m_api;
	m_templates_tree->m_wf_mgr=m_wf_mgr;
	m_templates_tree->m_parent_select_dlg=this;

//	m_templates_frame->m_api=m_api;
	m_templates_frame->m_wf_mgr=m_wf_mgr;
	m_templates_frame->m_view->m_wf_mgr=m_wf_mgr;
	m_templates_frame->m_view->m_api=m_api;

	if(0 != m_sel_template)
	{
		if(m_api->m_data.IsKindOf(m_sel_template, m_wf_mgr->e_activity))
		{
			m_sel_activity = m_sel_template;
			m_api->m_data.GetAttr(m_sel_activity, m_wf_mgr->a_act_tmpl_proc_tmpl, m_sel_template);
		}
	}
	// Для удобства пользователя - сначала ждем, что выбрано то что надо, а потом разрешаетм нажать на Ok
	m_ok_btn.EnableWindow(FALSE);

	if((m_SelectMode&APL_MODE_WFL_SELECT_TEMPLATE) > 0 && (m_SelectMode&APL_MODE_WFL_SELECT_ACTIVITI) > 0 )
	{
		SetWindowText(APL_T("Выбор шаблона процесса или действия"));
	}
	else if((m_SelectMode&APL_MODE_WFL_SELECT_ACTIVITI) > 0 )
	{
		SetWindowText(APL_T("Выбор действия"));
	}

	if(!m_bShowAllTemplates && !m_bEditorMode) FilterTemplates();

	m_templates_tree->m_templates.Append(m_templates);
	
	m_templates_tree->UpdateTemplates();

	m_filtrEdit.SetWindowText(m_sLastFilter);
	m_FindEdit.SetWindowText(m_sLastFind);

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}


void CSelectProcessTemplDlg::OnOK() 
{
	// TODO: Add extra validation here
	if((m_SelectMode&APL_MODE_WFL_SELECT_ACTIVITI) > 0 && 0 != m_templates_frame->m_view->m_task_for_sel)
	{
		m_sel_template = m_templates_frame->m_view->m_task_for_sel;
	}
	else if((m_SelectMode&APL_MODE_WFL_SELECT_TEMPLATE) > 0 && 0 != m_templates_frame->m_view->m_prc)
	{
		m_sel_template = m_templates_frame->m_view->m_prc;
	}
	else
	{
		if((m_SelectMode&APL_MODE_WFL_SELECT_TEMPLATE) > 0 && (m_SelectMode&APL_MODE_WFL_SELECT_ACTIVITI) > 0 )
		{
			AfxMessageBox(APL_T("Выберите шаблон процесса или действие."), MB_OK|MB_ICONERROR);
		}
		else if((m_SelectMode&APL_MODE_WFL_SELECT_ACTIVITI) > 0 )
		{
			AfxMessageBox(APL_T("Выберите действие."), MB_OK|MB_ICONERROR);
		}
		else
		{
			AfxMessageBox(APL_T("Выберите шаблон процесса."), MB_OK|MB_ICONERROR);
		}
		return;
	}
	
	m_iEditorResultMode=3;

	/* ayatsk 30.01.2008 Иначе по шаблону нельзя запустить процесс.
	if(m_sel_template->GetAccessmode()>=aplRO)
	{
		AfxMessageBox(APL_T("У Вас недостаточно прав для изменения этого шаблона !!!\n"),MB_OK|MB_ICONSTOP);
		return;
	}*/

	CaplInstance *user;
	CString name,buf;
	m_api->m_data.GetAttr(m_templates_frame->m_view->m_prc,m_wf_mgr->a_proc_tmpl_editor,user);
	if(user!=0)
	{
		
		name+=APL_T(" Данный шаблон редактирует ");
		m_api->LoadItemInfo(user);
		m_api->m_appr_mgr.GetPersonName(user,buf);
		name+=buf;
		name+=APL_T("! \n\nПродолжить ?");
		if(IDYES!=AfxMessageBox(name,MB_ICONSTOP|MB_YESNO)) return;
	}
	
	CaplResizableDialog::OnOK();
}

void CSelectProcessTemplDlg::ExitFromTree(int code)
{
	if(code==4) {OnDelete(); return;}
	m_iEditorResultMode=code;
	m_sel_template=m_templates_frame->m_view->m_prc;

	if(!m_sel_template)
	{
		AfxMessageBox(APL_T("Выберите шаблон процесса."), MB_OK|MB_ICONERROR);
		return;
	}
	CaplResizableDialog::OnOK();
}

void CSelectProcessTemplDlg::OnChange() 
{
	OnOK();
	//m_iEditorResultMode=3;
	//m_sel_template=m_templates_frame->m_view->m_prc;
	//CaplResizableDialog::OnOK();
}

void CSelectProcessTemplDlg::OnCreateNew() 
{
	m_iEditorResultMode=1;
	m_sel_template=0;
	CaplResizableDialog::OnOK();
}

void CSelectProcessTemplDlg::OnCreateCopy() 
{
	m_iEditorResultMode=2;
	m_sel_template=m_templates_frame->m_view->m_prc;
	if(!m_sel_template)
	{
		AfxMessageBox(APL_T("Выберите шаблон процесса."), MB_OK|MB_ICONERROR);
		return;
	}
	CaplResizableDialog::OnOK();
}


void CSelectProcessTemplDlg::OnDelete() 
{
	//if(IDYES!=AfxMessageBox(APL_T("Вы действительно хотите удалить шаблон процесса ?"),MB_YESNO|MB_ICONSTOP)) return;
	m_sel_template=m_templates_frame->m_view->m_prc;
	if(!m_sel_template)
	{
		AfxMessageBox(APL_T("Выберите шаблон процесса."), MB_OK|MB_ICONERROR);
		return;
	}
	if(m_wf_mgr->DeleteProcessTemplate(m_templates_frame->m_view->m_prc,true))
	{
		m_templates_frame->m_view->ShowTemplate(0,0);
		m_templates_tree->UpdateTemplates();
	}
	//Refresh();

	
}

void CSelectProcessTemplDlg::FilterTemplates()
{
	aplExtent aeHolders;
	bool bUserCanStartIt = false;
	CaplInstance *ciOwner = m_api->m_appr_mgr.GetCurrentPerson();
	CaplInstance *ciCurrUser = m_api->m_data.GetCurrUser();

	for(int i=0; i<m_templates.GetSize(); i++)
	{
		aeHolders.Clear();
		m_api->m_data.GetAttr(m_templates[i], m_wf_mgr->a_proc_tmpl_holders, aeHolders);

		bUserCanStartIt = false;
		for(int j= 0; j<aeHolders.GetSize(); j++)
		{
			if(aplIsPersonOrgElement(m_api, aeHolders[j], ciOwner))
			{
				bUserCanStartIt= true;
				break;
			}
		}

		if(!bUserCanStartIt) { m_templates.Remove(i); i--; }
	}						
}

//************************************************************************

void CSelectProcessTemplDlg::OnBnClickedFind(){FindInTre(0);}
void CSelectProcessTemplDlg::OnBnClickedFindBottom(){FindInTre(1);}
void CSelectProcessTemplDlg::OnBnClickedFindTop(){FindInTre(-1);}

void CSelectProcessTemplDlg::FindInTre(int delta)
{
	CString str;
	m_FindEdit.GetWindowText(str);
	if(str==_T("")){AfxMessageBox(_T("Не задан текст для поиска!"),MB_OK|MB_ICONINFORMATION);m_FindEdit.SetFocus(); return;}


	CTreeCtrl &tree=m_templates_tree->GetTreeCtrl();

	HTREEITEM cur_hitem=0; //TVI_ROOT;
	HTREEITEM next_hitem=0;
	if(0!=delta) cur_hitem=tree.GetSelectedItem();

	next_hitem=cur_hitem;

	if(0!=cur_hitem) 
	{
		// Ищем родителя
		while(true)
		{
			HTREEITEM parent=tree.GetNextItem(next_hitem,TVGN_PARENT);
			if(0==parent) break;
			next_hitem=parent;
		}
	}

	str.MakeLower();
	CString buf;
	if(0==delta) delta=1;

	UINT deltacode=TVGN_NEXT;
	if(delta<0) deltacode=TVGN_PREVIOUS;

	while(true)
	{
		if(0==next_hitem) next_hitem = tree.GetNextItem(next_hitem,TVGN_CHILD);
		else next_hitem = tree.GetNextItem(next_hitem,deltacode);

		if(0==next_hitem) return;

		bool bFound=false;
		buf=tree.GetItemText(next_hitem);
		buf.MakeLower();

		if(buf.Find(str)>=0)
		{
			if(0!=cur_hitem)
			{
				tree.SetItemState(cur_hitem, 0, TVIS_SELECTED|TVIS_DROPHILITED);
			}
			//tree.SingleSelectItem(next_hitem);
			//tree.SetItemState(next_hitem,  TVIS_SELECTED|TVIS_DROPHILITED, TVIS_SELECTED|TVIS_DROPHILITED);
			//tree.SelectItem(next_hitem);
			tree.SetItemState(next_hitem, TVIS_SELECTED, TVIS_SELECTED);
			tree.SelectItem(next_hitem);
			tree.SelectDropTarget(next_hitem);
			tree.SetFocus();
			tree.EnsureVisible(next_hitem);
			return;
		}
	}
}

//************************************************************************

void CSelectProcessTemplDlg::OnBnClickedFiltr()
{
	m_templates_tree->m_templates.Clear();

	CString str;
	m_filtrEdit.GetWindowText(str); str.MakeLower();

	if(str==_T("")) m_templates_tree->m_templates.Append(m_templates);
	else
	{
		CString sId, sName;
		aplExtent ext_filtered_templates;

		for(int i=0; i<m_templates.GetSize(); i++)
		{
			CaplInstance *teml=m_templates[i];
			m_api->m_data.GetAttr(teml, m_wf_mgr->a_action_id, sId);
			m_api->m_data.GetAttr(teml, m_wf_mgr->a_action_name, sName);
			sId.MakeLower();
			sName.MakeLower();
			if(sId.Find(str)>=0 || sName.Find(str)>=0) ext_filtered_templates.Add(teml);
		}
		if(ext_filtered_templates.GetSize()>0) m_templates_tree->m_templates.Append(ext_filtered_templates);
		else
		{
			AfxMessageBox(_T("Нет шаблонов с указанной подстрокой.\n\nПоказаны все шаблоны."),MB_OK|MB_ICONINFORMATION);
			m_templates_tree->m_templates.Append(m_templates);
		}
	}
	m_templates_tree->UpdateTemplates();
}



void CSelectProcessTemplDlg::OnDestroy()
{
	m_filtrEdit.GetWindowText(m_sLastFilter);
	m_FindEdit.GetWindowText(m_sLastFind);

	CaplResizableDialog::OnDestroy();
}
