#include"FTP.h"

bool CFTP::Polacz(CString ftpServer,CString login, CString pass,CListCtrl & list)
{
	WIN32_FIND_DATA  pKatalogInfo;

	void * pTemp = NULL;
	hInternet = InternetOpen (L"ftp",INTERNET_OPEN_TYPE_PRECONFIG, 0,0,0); 

	if(hInternet == NULL) return false;

	if(login.IsEmpty() || pass.IsEmpty())
		hFTP = InternetConnect(hInternet,ftpServer,INTERNET_DEFAULT_FTP_PORT,NULL,NULL,
			INTERNET_SERVICE_FTP,0,0);
	else
		hFTP = InternetConnect(hInternet,ftpServer,INTERNET_DEFAULT_FTP_PORT,login,pass,
			INTERNET_SERVICE_FTP,0,0);
	
	if(hFTP == NULL) return false;

	hFile = FtpFindFirstFile(hFTP,NULL,&pKatalogInfo,0,0);

	if ( hFile == NULL )
	{
		MessageBox(0,L"Błąd funkcji FtpFindFirstFile",L"",MB_OK);
		return false;
	}
	else
	{
		int licz = 0;
		while(!(GetLastError() == ERROR_NO_MORE_FILES))
		{
			int index = list.InsertItem(licz,pKatalogInfo.cFileName);

			if(pKatalogInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				list.SetItem(index, 1, LVIF_TEXT,L"Katalog", 0, 0, 0, NULL);
			else
				list.SetItem(index, 1, LVIF_TEXT,L"Plik", 0, 0, 0, NULL);

			bool b = InternetFindNextFile(hFile,&pKatalogInfo);
			licz++;
		}
	}
	return true;
}

bool CFTP::ZakonczPolaczenie()
{
	if(hInternet != NULL && hFTP != NULL && hFile != NULL)
	{
		InternetCloseHandle( hFile );
		hFile = NULL;
		InternetCloseHandle(hFTP);
		hFTP = NULL;
		InternetCloseHandle(hInternet);
		hInternet = NULL;
		return true;
	}
	return false;
}

bool CFTP::DodajPlik(CString plikLokalny, CString plikFTP)
{
    if(!hFTP) return false;

    if(!FtpPutFile(hFTP,plikLokalny,plikFTP,FTP_TRANSFER_TYPE_BINARY,0)) return false;
	return true;
}

bool CFTP::PobierzPlik(CString plikFTP,CString plikLokal)
{
	if(!hFTP) return false;

	if(!FtpGetFile(hFTP,plikFTP,plikLokal,false,FILE_ATTRIBUTE_NORMAL,
		FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_RELOAD,0))
		return false;
	return true;
}