// SubscriptionDlg.cpp : implementation file
//

#include "stdafx.h"
#include "psm.h"
#include "psmdoc.h"
#include "SubscriptionDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CSubscriptionDlg dialog

int CALLBACK CompFn(LPARAM p1, LPARAM p2, LPARAM api)
{
	CaplAPI *m_api = (CaplAPI*)api;
	CaplInstance* inst1 = (CaplInstance*)p1;
	CaplInstance* inst2 = (CaplInstance*)p2;
	m_api->m_data.GetAttr(inst1,m_api->m_message_mgr.a_subscr_item,inst1);
	m_api->m_data.GetAttr(inst2,m_api->m_message_mgr.a_subscr_item,inst2);
	int type1=0;
	int type2=0;
	if(m_api->m_data.IsKindOf(inst1,m_api->m_doc_mgr.e_doc)) type1 = 1;
	else if(m_api->m_data.IsKindOf(inst1,m_api->m_bp_mgr.e_bp)) type1 = 2;
	else if(m_api->m_data.IsKindOf(inst1,m_api->m_categ_mgr.e_categ)) type1 = 3;
	if(m_api->m_data.IsKindOf(inst2,m_api->m_doc_mgr.e_doc)) type2 = 1;
	else if(m_api->m_data.IsKindOf(inst2,m_api->m_bp_mgr.e_bp)) type2 = 2;
	else if(m_api->m_data.IsKindOf(inst2,m_api->m_categ_mgr.e_categ)) type2 = 3;
	if(type2>type1) return -1;
	if(type2<type1) return 1;
	CString name1, name2;
	m_api->GetItemName(inst1,name1);
	m_api->GetItemName(inst2,name2);
	if(name2>name1) return -1;
	if(name2<name1) return 1;
	return 0;
}

CSubscriptionDlg::CSubscriptionDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CSubscriptionDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSubscriptionDlg)
	//}}AFX_DATA_INIT

	m_api = NULL;

	m_curItem= NULL;
	m_index= -1;
}


void CSubscriptionDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSubscriptionDlg)
	DDX_Control(pDX, IDOK, m_okBtn);
	DDX_Control(pDX, IDCANCEL, m_cancelBtn);
	DDX_Control(pDX, IDC_DELETE_SUBSCR, m_deleteBtn);
	DDX_Control(pDX, IDC_ADD_SUBSCR, m_addBtn);
	DDX_Control(pDX, IDC_SUBSCR_LIST, m_list);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CSubscriptionDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CSubscriptionDlg)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_SUBSCR_LIST, OnItemchangedSubscrList)
	ON_BN_CLICKED(IDC_ADD_SUBSCR, OnAddSubscr)
	ON_BN_CLICKED(IDC_DELETE_SUBSCR, OnDeleteSubscr)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSubscriptionDlg message handlers

void CSubscriptionDlg::OnOK() 
{
	// TODO: Add extra validation here
	if(m_api->m_data.IsConnected())
	{
		int i;
		bool bSave= false;
		for(i= 0; i<m_del_items.GetSize(); i++)
		{m_api->m_message_mgr.DeleteSubscribe(m_del_items[i], false);bSave= true;}
		for(i= 0; i<m_new_items.GetSize(); i++)
		{m_api->m_message_mgr.CreateSubscribe(m_new_items[i], NULL, false);bSave= true;}
		if(bSave) m_api->m_data.NET_SaveChanges();
	}
	
	CaplResizableDialog::OnOK();
}

void CSubscriptionDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CaplResizableDialog::OnCancel();
}

void CSubscriptionDlg::OnItemchangedSubscrList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	// TODO: Add your control notification handler code here
	m_index= m_list.GetNextItem(-1, LVNI_ALL|LVNI_SELECTED);
	if(-1!=m_index)
	{
		m_curItem= (CaplInstance*)m_list.GetItemData(m_index);
		if(m_curItem)
			m_deleteBtn.EnableWindow();
	}
	else
	{
		m_curItem= NULL;
		m_deleteBtn.EnableWindow(FALSE);
	}
	*pResult = 0;
}

void CSubscriptionDlg::OnAddSubscr() 
{
	if(!m_api->m_data.IsConnected()) return;

	CaplInstance* item= m_api->m_message_mgr.SelectInstance(APL_MODE_SELECT_DOC|APL_MODE_SELECT_PDF|APL_MODE_SELECT_BP|APL_MODE_SELECT_CATEGORY, 
		 APL_T("Выберите объект подписки"));
	if(item)
	{
		bool bNew= true;
		for(int i= 0; i<m_subscr_items.GetSize(); i++)
		{
			CaplInstance* inst= NULL;
			m_api->m_data.GetAttr(m_subscr_items[i], m_api->m_message_mgr.a_subscr_item, inst);
			if(inst==item)
			{
				CaplInstance* sbscr= m_api->m_message_mgr.CreateSubscribe(item);
				if(sbscr)
				{
					int n= m_del_items.Find(sbscr);//передумал удалять
					if(-1!=n)
						m_del_items.Remove(n);
				}
				bNew= false;
				break;
			}
		}
		
		if(bNew && -1==m_new_items.Find(item))
			m_new_items.Add(item);
		
		ShowSbscrList();
	}
}

void CSubscriptionDlg::OnDeleteSubscr() 
{
	if(!m_api->m_data.IsConnected()) return;

	if(m_curItem)
	{
		int n= -1;
		n= m_subscr_items.Find(m_curItem);
		if(-1!=n)
			m_del_items.Add(m_curItem);
		else
		{
			n= m_new_items.Find(m_curItem);
			if(-1!=n)
				m_new_items.Remove(n);
		}

		ShowSbscrList();
	}
}

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

	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	
	//ICON_DOCUMENT_REV+1
	if(m_api==0)
	{
#ifdef _DEBUG
		AfxMessageBox( APL_T("Не задан m_api"));
#endif
		EndDialog(0);
		return FALSE;
	}
	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(&(m_api->m_data));

	m_cancelBtn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancelBtn.SetFlat(FALSE);
	m_okBtn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_okBtn.SetFlat(FALSE);
	m_addBtn.SetIcon(GetAplStdIco16(APLSTDICO_PLUS));
	m_addBtn.SetFlat(FALSE);
	m_deleteBtn.SetIcon(GetAplStdIco16(APLSTDICO_MINUS));
	m_deleteBtn.SetFlat(FALSE);
	m_deleteBtn.EnableWindow(FALSE);
	
	m_imageList.Create(aplGetInstImageList());
	
	m_list.SetImageList(&m_imageList, LVSIL_SMALL);
	m_list.SetExtendedStyle(m_list.GetExtendedStyle()|LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES);
	
	m_list.InsertColumn(0, APL_T("Элемент подписки"), LVCFMT_LEFT, 300);
	m_list.InsertColumn(1, APL_T("Тип элемента"), LVCFMT_LEFT, 100);
	m_list.InsertColumn(2, APL_T("Событие"), LVCFMT_LEFT, 200);
	
	AddAnchor(IDC_SUBSCR_LIST,TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_SBSCR_STATIC,TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_DELETE_SUBSCR,TOP_RIGHT);
	AddAnchor(IDC_ADD_SUBSCR,TOP_RIGHT);	
	AddAnchor(IDOK,BOTTOM_RIGHT);	
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);	
	
	// TODO: Add extra initialization here
	ShowSbscrList();

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

bool CSubscriptionDlg::ShowSbscrList()
{
	CString name, type, event, buf;
	int i, ico;
	
	m_list.DeleteAllItems();
	for(i= 0; i<m_subscr_items.GetSize(); i++) //сначала весь список...
	{
		if(!m_subscr_items[i]) continue;
		if(-1!=m_del_items.Find(m_subscr_items[i])) continue; //...за исключением удаляемых
		CaplInstance* inst= NULL;
		m_api->m_data.GetAttr(m_subscr_items[i], m_api->m_message_mgr.a_subscr_item, inst);
		if(!inst) continue;
		
		name.Empty();
		ico= -1;

		if(m_api->m_data.IsKindOf(inst,m_api->m_doc_mgr.e_doc))
		{
			type=  APL_T("Документ");
			event=  APL_T("Изменение активной версии");
			m_api->m_doc_mgr.LoadDocInfo(inst);
			m_api->GetItemName(inst,name);
			ico= ICON_DOCUMENT;
		}
		else if(m_api->m_data.IsKindOf(inst,m_api->m_prd_mgr.e_pdf))
		{
			type=  APL_T("Версия изделия");
			event=  APL_T("Изменение состава изделия");
			
			m_api->m_prd_mgr.LoadPrdInfo(inst);
			m_api->GetItemName(inst,name);
			ico= ICON_ASSEMBLY;
					
			m_api->m_data.GetAttr(inst, m_api->m_prd_mgr.a_apl_pdf_type, buf);
			if(buf==_T("part")) ico= ICON_PART;
			if(buf==_T("material")) ico= ICON_MATERIAL;
			if(buf==_T("kit")) ico= ICON_KIT;
			if(buf==_T("komplex")) ico= ICON_KOMPLEX;
			if(buf==_T("other")) ico= ICON_OTHER;
		}
		else if(m_api->m_data.IsKindOf(inst,m_api->m_bp_mgr.e_bp))
		{
			m_api->m_bp_mgr.LoadBPInfo(inst);
			type=  APL_T("Бизнес процесс");
			event=  APL_T("Изменение активной версии");
			m_api->GetItemName(inst, name);
			ico = ICON_BP;
		}
		else if(m_api->m_data.IsKindOf(inst,m_api->m_categ_mgr.e_categ))
		{
			m_api->m_categ_mgr.LoadCategoryInfo(inst);
			type=  APL_T("Категория");
			event=  APL_T("Изменение содержимого");
			m_api->GetItemName(inst, name);
			ico = ICON_CATEGORIES;
		}
		if(!name.IsEmpty())
		{
			int n= m_list.GetItemCount();
			int m= m_list.InsertItem(n, name, ico);
			m_list.SetItemData(m, (DWORD)m_subscr_items[i]);
			m_list.SetItemText(m, 1, type);
			m_list.SetItemText(m, 2, event);
		}
	}
	for(i= 0; i<m_new_items.GetSize(); i++)
	{
		if(!m_new_items[i]) continue;
		
		if(m_api->m_data.IsKindOf(m_new_items[i],m_api->m_doc_mgr.e_doc))
		{
			type=  APL_T("Документ");
			event=  APL_T("Изменение активной версии");
			m_api->GetItemName(m_new_items[i],name);
			ico= ICON_DOCUMENT_REV+1;
		}
		else if(m_api->m_data.IsKindOf(m_new_items[i],m_api->m_prd_mgr.e_pdf))
		{
			type=  APL_T("Версия изделия");
			event=  APL_T("Изменение состава изделия");
			
			m_api->GetItemName(m_new_items[i],name);
			ico= ICON_ASSEMBLY;
					
			m_api->m_data.GetAttr(m_new_items[i], m_api->m_prd_mgr.a_apl_pdf_type, buf);
			if(buf==_T("part")) ico= ICON_PART;
			if(buf==_T("material")) ico= ICON_MATERIAL;
			if(buf==_T("kit")) ico= ICON_KIT;
			if(buf==_T("komplex")) ico= ICON_KOMPLEX;
			if(buf==_T("other")) ico= ICON_OTHER;
		}
		else if(m_api->m_data.IsKindOf(m_new_items[i],m_api->m_bp_mgr.e_bp))
		{
			type=  APL_T("Бизнес процесс");
			event=  APL_T("Изменение активной версии");
			m_api->GetItemName(m_new_items[i], name);
			ico = ICON_BP;
		}
		else if(m_api->m_data.IsKindOf(m_new_items[i],m_api->m_categ_mgr.e_categ))
		{
			type=  APL_T("Категория");
			event=  APL_T("Изменение изменение содержимого");
			m_api->GetItemName(m_new_items[i], name);
			ico = ICON_CATEGORIES;
		}
		if(!name.IsEmpty())
		{
			int n= m_list.GetItemCount();
			int m= m_list.InsertItem(n, name, ico);
			m_list.SetItemData(m, (DWORD)m_new_items[i]);
			m_list.SetItemText(m, 1, type);
			m_list.SetItemText(m, 2, event);
		}		
	}
	m_list.SortItems(CompFn,(DWORD)m_api);
	return true;
}
