// NoticeTrans.cpp : 구현 파일입니다.
//

#include "stdafx.h"
#include "ConsoleTransfer.h"
#include "NoticeTrans.h"
#include ".\noticetrans.h"
#include "../CommLib/CommLib.h"

// CNoticeTrans 대화 상자입니다.

IMPLEMENT_DYNAMIC(CNoticeTrans, CDialog)
CNoticeTrans::CNoticeTrans(CWnd* pParent /*=NULL*/)
	: CDialog(CNoticeTrans::IDD, pParent)
{
}


CNoticeTrans::CNoticeTrans(PTRANPARAM_STRUCT ptp, CString szTargetPath , CWnd* pParent /*=NULL*/ )
: CDialog(CNoticeTrans::IDD, pParent)
{

	m_szTargetPath = szTargetPath;
	m_NoticeLastFileTrans = false;
//	m_szTargetPath.Replace("'", "\'");
	
	m_ptp = ptp;
}

CNoticeTrans::CNoticeTrans(PTRANPARAM_STRUCT ptp, int nNoticeLastFileTrans , CWnd* pParent /*=NULL*/ )
: CDialog(CNoticeTrans::IDD, pParent)
{

	m_szTargetPath = "";
	m_NoticeLastFileTrans = true;

	m_ptp = ptp;
}



CNoticeTrans::~CNoticeTrans()
{
	delete m_ptp;
}

void CNoticeTrans::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_PROGRESS1, m_NoticeProgress);
	DDX_Control(pDX, IDC_NOTICE_MSGBOX, m_NoticeText);
	
}


BEGIN_MESSAGE_MAP(CNoticeTrans, CDialog)
	ON_MESSAGE(WMU_NOTICE_TRANS, OnNoticeTrans)
	ON_MESSAGE(WMU_NOTICE_LAST_FILE_TRANS, OnNoticeLastFileTrans)
	ON_BN_CLICKED(IDCANCEL, OnBnClickedCancel)
//	ON_STN_CLICKED(IDC_NOTICE_MSGBOX, OnStnClickedNoticeMsgbox)
END_MESSAGE_MAP()


// CNoticeTrans 메시지 처리기입니다.
void CNoticeTrans::NoticeTrans(void)
{	
	tsvc_req_header_t tsvc_req_header;
	tsvc_auth_info_t auth_req_body;
	tsvc_dn_req_body_t dn_req_body;
	tsvc_rsp_header_t *tsvc_rsp_header_ptr;
	char recv_buffer[8196];
	int result_code;
	CString ip;
	CString this_guid;


	SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock == INVALID_SOCKET) {
		SetNoticeStep(101);
		goto EXIT_FUNCTION;
	}
	
	SetNoticeStep(100);

	bool bRet = false;
	DWORD dwWritten;
	char s[1024];

	sockaddr_in sa; 
	sa.sin_family      = AF_INET;
	
	ip = m_sutil.get_first_rcts(m_ptp->szRCTSAddress);
	if (ip.GetLength()>0)
		sa.sin_addr.s_addr = m_sutil.conv_addr(ip.GetString());
	else
		goto EXIT_FUNCTION;

	//sa.sin_addr.s_addr = conv_addr("222.122.181.9");

	sa.sin_port        = htons(RCTS_NOTICE_PORT);

/*
	int nNonBlocking = 1;
	ioctlsocket(sock, FIONBIO, (u_long FAR*)&nNonBlocking);
*/


	connect(sock, (SOCKADDR*)&sa, sizeof(sa));
	

	tsvc_req_header.op_num_w = ::htons(OP_NUM_AUTH);
	tsvc_req_header.op_seq_w = ::htons(OP_SEQ_REQ);

	::sprintf(auth_req_body.ua_str, m_ptp->szUserId);
	::sprintf(auth_req_body.up_str, m_ptp->szPassword);
	
	m_sutil._sh_send(sock, (char*)&tsvc_req_header, sizeof(tsvc_req_header));
	m_sutil._sh_send(sock, (char*)&auth_req_body, sizeof(auth_req_body));
	
	memset(recv_buffer , 0x00 , sizeof(recv_buffer));
	if (m_sutil._rtxTimer(5 , sock) < 0)
		goto EXIT_FUNCTION;
	m_sutil._sh_recv(sock, (char*)&recv_buffer, sizeof(recv_buffer));

	tsvc_rsp_header_ptr = reinterpret_cast<tsvc_rsp_header_t *>(&recv_buffer);
	result_code = ntohs(tsvc_rsp_header_ptr->op_result_code_w);
	
	// 인증
	if (RSP_CODE_AUTH_SUCCESS==result_code)
	{
		SetNoticeStep(200);
	}
	else
	{
		SetNoticeStep(201);
		goto EXIT_FUNCTION;
	}
	
	tsvc_req_header.op_num_w = ::htons(OP_NUM_DN);
	tsvc_req_header.op_seq_w = ::htons(OP_SEQ_REQ);
	
	memset(&dn_req_body , 0x00 , sizeof(dn_req_body));
	dn_req_body.op_mode_w = htons(OP_DN_MODE_REQ);
	::sprintf(dn_req_body.uri_str  ,"%s", m_szTargetPath);
	::strncpy(dn_req_body.sp_tid_str , m_ptp->szTransGuid , MAX_SIZE_OF_SP_TID-1);

	m_sutil._sh_send(sock,(char *)&tsvc_req_header, sizeof(tsvc_req_header));
	m_sutil._sh_send(sock,(char *)&dn_req_body, sizeof(tsvc_dn_req_body_t));

	SetNoticeStep(300);
	
	memset(recv_buffer , 0x00 , sizeof(recv_buffer));
	if (m_sutil._rtxTimer(5 , sock) < 0)
		goto EXIT_FUNCTION;
	m_sutil._sh_recv(sock, (char*)&recv_buffer, sizeof(recv_buffer));
	
	tsvc_rsp_header_ptr = reinterpret_cast<tsvc_rsp_header_t *>(&recv_buffer);
	result_code = ntohs(tsvc_rsp_header_ptr->op_result_code_w);
	int result_opn = ntohs(tsvc_rsp_header_ptr->op_num_w);

	//배포
	if (RSP_CODE_DIST_SUCCESS==result_code)
	{
		SetNoticeStep(400);
	}
	else
	{

		SetNoticeStep(401);
		goto EXIT_FUNCTION;
	}

EXIT_FUNCTION:	
	
	if (sock != INVALID_SOCKET)
		closesocket(sock);

	PostMessage(WM_CLOSE);
}

void CNoticeTrans::LastFileTransComplete()
{
	tsvc_req_header_t tsvc_req_header;
	tsvc_auth_info_t auth_req_body;
	tsvc_dn_req_body_t dn_req_body;
	tsvc_ddc_req_body_t dnc_req_body;
	tsvc_rsp_header_t *tsvc_rsp_header_ptr;
	char recv_buffer[8196];
	int result_code;
	CString ip;
	CString this_guid;

	SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock == INVALID_SOCKET) {
		SetNoticeStep(103);
		goto EXIT_FUNCTION;
	}

	SetNoticeStep(102);

	bool bRet = false;
	DWORD dwWritten;
	char s[1024];

	sockaddr_in sa; 
	sa.sin_family      = AF_INET;

	ip = m_sutil.get_first_rcts(m_ptp->szRCTSAddress);
	if (ip.GetLength()>0)
		sa.sin_addr.s_addr = m_sutil.conv_addr(ip.GetString());
	else
		goto EXIT_FUNCTION;

	sa.sin_port        = htons(RCTS_NOTICE_PORT);

	connect(sock, (SOCKADDR*)&sa, sizeof(sa));


	//////////////////////////////////////////////////////////////////////////////////
	// 인증
	//////////////////////////////////////////////////////////////////////////////////

	tsvc_req_header.op_num_w = ::htons(OP_NUM_AUTH);
	tsvc_req_header.op_seq_w = ::htons(OP_SEQ_REQ);

	::sprintf(auth_req_body.ua_str, m_ptp->szUserId);
	::sprintf(auth_req_body.up_str, m_ptp->szPassword);

	m_sutil._sh_send(sock, (char*)&tsvc_req_header, sizeof(tsvc_req_header));
	m_sutil._sh_send(sock, (char*)&auth_req_body, sizeof(auth_req_body));

	memset(recv_buffer , 0x00 , sizeof(recv_buffer));
	if (m_sutil._rtxTimer(5 , sock) < 0)
		goto EXIT_FUNCTION;
	m_sutil._sh_recv(sock, (char*)&recv_buffer, sizeof(recv_buffer));

	tsvc_rsp_header_ptr = reinterpret_cast<tsvc_rsp_header_t *>(&recv_buffer);
	result_code = ntohs(tsvc_rsp_header_ptr->op_result_code_w);

	if (RSP_CODE_AUTH_SUCCESS==result_code)
	{
		SetNoticeStep(202);
	}
	else
	{
		SetNoticeStep(203);
		goto EXIT_FUNCTION;
	}
	//////////////////////////////////////////////////////////////////////////////////
	// 인증 끝
	//////////////////////////////////////////////////////////////////////////////////


	//////////////////////////////////////////////////////////////////////////////////
	// 전송완료알림//////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////
	tsvc_req_header.op_num_w = ::htons(OP_NUM_DNC);
	tsvc_req_header.op_seq_w = ::htons(OP_SEQ_REQ);

	m_sutil._sh_send(sock,(char *)&tsvc_req_header, sizeof(tsvc_req_header));
	SetNoticeStep(302);
	//////////////////////////////////////////////////////////////////////////////////
	// 전송완료알림 끝////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////////////////
	// 관리자 정보
	//////////////////////////////////////////////////////////////////////////////////
	memset(&dnc_req_body , 0x00 , sizeof(dnc_req_body));
	::strncpy(dnc_req_body.sp_tid_str , m_ptp->szTransGuid , MAX_SIZE_OF_SP_TID-1);

	FillAdminInfo(&dnc_req_body);

	m_sutil._sh_send(sock,(char *)&dnc_req_body, sizeof(tsvc_dn_req_body_t));

	memset(recv_buffer , 0x00 , sizeof(recv_buffer));
	if (m_sutil._rtxTimer(5 , sock) < 0)
		goto EXIT_FUNCTION;
	m_sutil._sh_recv(sock, (char*)&recv_buffer, sizeof(recv_buffer));

	tsvc_rsp_header_ptr = reinterpret_cast<tsvc_rsp_header_t *>(&recv_buffer);
	result_code = ntohs(tsvc_rsp_header_ptr->op_result_code_w);
	
	if (RSP_CODE_DIST_SUCCESS==result_code)
	{
		SetNoticeStep(402);
	}
	else
	{
		SetNoticeStep(403);
		goto EXIT_FUNCTION;
	}
	//////////////////////////////////////////////////////////////////////////////////
	// 관리자 정보 끝
	//////////////////////////////////////////////////////////////////////////////////


EXIT_FUNCTION:	

	if (sock != INVALID_SOCKET)
		closesocket(sock);

	PostMessage(WM_CLOSE);
}


BOOL CNoticeTrans::OnInitDialog()
{
	CDialog::OnInitDialog();

	// TODO:  여기에 추가 초기화 작업을 추가합니다.
	m_NoticeProgress.SetRange(0, 100);
	m_NoticeProgress.SetStep(1);
	
	if (m_NoticeLastFileTrans)
		this->PostMessage(WMU_NOTICE_LAST_FILE_TRANS , NULL , NULL);
	else
		this->PostMessage(WMU_NOTICE_TRANS , NULL , NULL);

	return TRUE;  // return TRUE unless you set the focus to a control
	// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}


LRESULT CNoticeTrans::OnNoticeTrans(WPARAM wParam, LPARAM lParam)
{
	SetNoticeStep(0);

	while (FALSE==IsWindowVisible())
	{
		m_sutil.MessagePump(100);
	}

	this->NoticeTrans();

	return 0;
}

LRESULT CNoticeTrans::OnNoticeLastFileTrans(WPARAM wParam, LPARAM lParam)
{
	SetNoticeStep(2);

	while (FALSE==IsWindowVisible())
	{
		m_sutil.MessagePump(100);
	}

	this->LastFileTransComplete();

	return 0;
}


void CNoticeTrans::OnBnClickedCancel()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	OnCancel();
}

void CNoticeTrans::SetNoticeStep(int nStep)
{
	if (0==nStep)
	{
		m_NoticeProgress.SetPos(10);
		m_NoticeText.SetWindowText("배포 요청중입니다...(0/4 요청준비)");
	}
	if (2==nStep)
	{
		m_NoticeProgress.SetPos(10);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(0/4 요청준비)");
	}
	else if (100 == nStep)
	{
		m_NoticeProgress.SetPos(20);
		m_NoticeText.SetWindowText("배포 요청중입니다...(1/4 사용자인증)");

	}
	else if (102 == nStep)
	{
		m_NoticeProgress.SetPos(20);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(1/4 사용자인증)");

	}
	else if (200 == nStep)
	{
		m_NoticeProgress.SetPos(40);
		m_NoticeText.SetWindowText("배포 요청중입니다...(2/4 인증성공)");

	}
	else if (201 == nStep)
	{
		m_NoticeProgress.SetPos(40);
		m_NoticeText.SetWindowText("배포 요청을 중단합니다...(2/4 인증실패)");
		m_sutil.MessagePump(500);
	}
	else if (202 == nStep)
	{
		m_NoticeProgress.SetPos(40);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(2/4 인증성공)");

	}
	else if (203 == nStep)
	{
		m_NoticeProgress.SetPos(40);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(2/4 인증실패)");
	}
	else if (300 == nStep)
	{
		m_NoticeProgress.SetPos(70);
		m_NoticeText.SetWindowText("배포 요청중입니다...(3/4 배포요청)");

	}
	else if (302 == nStep)
	{
		m_NoticeProgress.SetPos(70);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(3/4 알림요청)");

	}
	else if (303 == nStep)
	{
		m_NoticeProgress.SetPos(70);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(3/4 요청실패)");

	}
	else if (400 == nStep)
	{
		m_NoticeProgress.SetPos(100);
		m_NoticeText.SetWindowText("배포를 시작합니다...(4/4 요청성공)");
		m_sutil.MessagePump(500);
	}
	else if (401 == nStep)
	{
		m_NoticeProgress.SetPos(100);
		m_NoticeText.SetWindowText("배포 요청을 중단합니다...(4/4 요청실패)");
		m_sutil.MessagePump(500);
	}
	else if (402 == nStep)
	{
		m_NoticeProgress.SetPos(100);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(4/4 요청성공)");
		m_sutil.MessagePump(500);
	}
	else if (403 == nStep)
	{
		m_NoticeProgress.SetPos(100);
		m_NoticeText.SetWindowText("현재 전송창을 종료합니다...(4/4 요청실패)");
		m_sutil.MessagePump(500);
	}

}



void CNoticeTrans::FillAdminInfo(tsvc_ddc_req_body_t* pDncInfo)
{

	strncpy(pDncInfo->name_01 ,m_ptp->name_01 , MAX_SIZE_OF_NAME-1) ;
	strncpy(pDncInfo->name_02 ,m_ptp->name_02 , MAX_SIZE_OF_NAME-1) ;
	strncpy(pDncInfo->name_03 ,m_ptp->name_03 , MAX_SIZE_OF_NAME-1) ;

	strncpy(pDncInfo->phone_01 ,m_ptp->phone_01 , MAX_SIZE_OF_PHONE-1) ;
	strncpy(pDncInfo->phone_02 ,m_ptp->phone_02 , MAX_SIZE_OF_PHONE-1) ;
	strncpy(pDncInfo->phone_03 ,m_ptp->phone_03 , MAX_SIZE_OF_PHONE-1) ;

	strncpy(pDncInfo->mail_01 ,m_ptp->mail_01 , MAX_SIZE_OF_MAIL-1) ;
	strncpy(pDncInfo->mail_02 ,m_ptp->mail_02 , MAX_SIZE_OF_MAIL-1) ;
	strncpy(pDncInfo->mail_03 ,m_ptp->mail_03 , MAX_SIZE_OF_MAIL-1) ;

}
