 /***************************************************************************************
 *This program is free software; you can redistribute it and/or modify					*
 * it under the terms of the GNU General Public License as published by					*
 * the Free Software Foundation; either version 2 of the License, or					*
 * (at your option) any later version.													*
 *																						*
 * The GPL can be found at: http://www.gnu.org/copyleft/gpl.html						*
 *																						*
 *																						*	
 ****************************************************************************************
 * Authors:																			  *
 *          Marc Dukette                                                              *
 **************************************************************************************/

#include "stdafx.h"
#include "PlaylistEditor.h"
#include <commctrl.h>
#include <commdlg.h>
#if (_WIN32_WCE >= 300 && !defined(HPC))
#include <aygshell.h>
#include <sipapi.h>
	#define SHCMBM_GETMENU      (WM_USER + 402)
	#define SHGetMenu( hWndMB )  ( HMENU )SendMessage( ( hWndMB ), SHCMBM_GETMENU, ( WPARAM )0, ( LPARAM )0 )
	#define CommandBar_GetMenu( hWndMB, x )		( HMENU )SendMessage( ( hWndMB ), SHCMBM_GETMENU, ( WPARAM )0, ( LPARAM )0 )
	typedef BOOL (CALLBACK* paygshell_SHCreateMenuBar)( SHMENUBARINFO *pmb );
	paygshell_SHCreateMenuBar aygshell_SHCreateMenuBar;
#endif
#ifdef GAPI
	#include "gx.h"
	GXKeyList g_gxk;
#endif

	LPTSTR ToolTips[9]={_T(""),_T("Open Playlist"),_T("Save"),_T("Add Item"),_T("Add Item URL"),_T("Delete Item"),_T("Play"),_T("Move Up"),_T("Move Down")};


#define MAX_LOADSTRING 100
extern int fnGetFileName(HWND Parent,LPTSTR Filter, LPTSTR initialDir, LPTSTR OutFileName, int MaxFilName,LPTSTR* szMultiBuff,unsigned int vk,int URL);

// Global Variables:
HINSTANCE			hInst;			// The current instance
HWND				hwndCB;			// The command bar handle
OPENFILENAME ofn;
HWND hwndList;
// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass	(HINSTANCE, LPTSTR);
BOOL				InitInstance	(HINSTANCE, int);
LRESULT CALLBACK	WndProc			(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK	About			(HWND, UINT, WPARAM, LPARAM);
//TCHAR file[200]={L"/my documents/untiltled.pdl"};
TCHAR		szFile[MAX_PATH] = TEXT("");
TCHAR		szPDLFile[MAX_PATH] = TEXT(".pdl\0");
TCHAR temp[200];
bool Edited=false;
#define REG_BASE_FMT			L"software\\PocketMVP\\plugins\\format"
TCHAR tfile[MAX_PATH];// = TEXT(".pdl\0");

void AddEntry(LPTSTR FileName, int pos)
{
	LVITEM lv;
	lv.mask=LVIF_TEXT;
	lv.pszText=_T("");
	lv.cchTextMax=1;
	lv.iSubItem=0;
	LPTSTR temp=FileName+wcslen(FileName);
	if (pos<0) lv.iItem=ListView_GetItemCount(hwndList);	
	else lv.iItem=pos;
	ListView_InsertItem(hwndList,&lv);
	while (temp[0]!='.')
	{
		temp--;
	}
	ListView_SetItemText(hwndList,lv.iItem,2,FileName);
	*temp=0;
	temp++;
	ListView_SetItemText(hwndList,lv.iItem,1,temp);
	while (temp[0]!='\\'&&(temp[0]!='/'))
	{
		temp--;
	}
	temp++;
	ListView_SetItemText(hwndList,lv.iItem,0,temp);
}

int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{
	MSG msg;
	HACCEL hAccelTable;

	// Perform application initialization:

	if (!InitInstance (hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_PLAYLISTEDITOR);
	if (lpCmdLine)
	{
		if (wcscmp(lpCmdLine,_T("")))
		{
			wcscpy(szPDLFile,lpCmdLine);
			if (wcsstr(szPDLFile,_T(".pdl")))
			{
				//wcscpy(file,ofn.lpstrFile);
				HANDLE h=CreateFile((LPCTSTR)szPDLFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
				int size=GetFileSize(h,NULL);
				unsigned long t;
				TCHAR* temp=(TCHAR*)malloc(size);
				TCHAR* EndPos=0;
				TCHAR* BeginPos=0;
				ReadFile(h,temp,size,&t,NULL);
				CloseHandle(h);
				BeginPos=temp;
				ListView_DeleteAllItems(hwndList);
				while(BeginPos<(temp+size) &&((EndPos=wcsstr(BeginPos,_T("\r")))!=NULL))
				{
					*EndPos=0;
					//SendMessage(hwndList,LB_ADDSTRING,0,(LPARAM)BeginPos);
					AddEntry(BeginPos,-1);
					BeginPos=EndPos+2;
				}
				free(temp);
			}
		}
	}

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
#ifdef GAPI
GXCloseInput();
#endif
	return msg.wParam;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    It is important to call this function so that the application 
//    will get 'well formed' small icons associated with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
	WNDCLASS	wc;

    wc.style			= CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc		= (WNDPROC) WndProc;
    wc.cbClsExtra		= 0;
    wc.cbWndExtra		= 0;
    wc.hInstance		= hInstance;
    wc.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PLAYLISTEDITOR));
    wc.hCursor			= 0;
    wc.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName		= 0;
    wc.lpszClassName	= szWindowClass;

	return RegisterClass(&wc);
}

//
//  FUNCTION: InitInstance(HANDLE, int)
//
//  PURPOSE: Saves instance handle and creates main window
//
//  COMMENTS:
//
//    In this function, we save the instance handle in a global variable and
//    create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND	hWnd;
	TCHAR	szTitle[MAX_LOADSTRING];			// The title bar text
	TCHAR	szWindowClass[MAX_LOADSTRING];		// The window class name

	hInst = hInstance;		// Store instance handle in our global variable
	// Initialize global strings
	LoadString(hInstance, IDC_PLAYLISTEDITOR, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance, szWindowClass);

	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	if (FindWindow(szWindowClass, szTitle))
	{
	   SetForegroundWindow(FindWindow(szWindowClass, szTitle));
	   return FALSE;
	}
	hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
		CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{	
		return FALSE;
	}
	RECT rc;
	GetClientRect(hWnd,&rc);
#if (_WIN32_WCE < 300 || defined(HPC))
	rc.top+=23;
	rc.bottom-=23;
#else
	rc.bottom-=26;
#endif

	
	hwndList=CreateWindow(_T("SysListView32"), _T(""), WS_VISIBLE|WS_CHILD|WS_VSCROLL|LVS_REPORT|LVS_SHOWSELALWAYS,
		rc.left, rc.top, rc.right, rc.bottom, hWnd, NULL, hInstance, NULL);
	if (!hwndList)
	{	
		return FALSE;
	}
	ListView_SetExtendedListViewStyle(hwndList,LVS_EX_FULLROWSELECT);
	LVCOLUMN lv;
	lv.mask=LVCF_TEXT | LVCF_WIDTH ;
	lv.fmt=LVCFMT_LEFT ;
	lv.cx=120;
	lv.pszText=_T("File");
	lv.cchTextMax=5;
	ListView_InsertColumn(hwndList,0,&lv);
	lv.cx=40;
	lv.pszText=_T("Type");
	ListView_InsertColumn(hwndList,1,&lv);
	lv.cx=80;
	lv.mask=LVCF_TEXT | LVCF_WIDTH | LVCF_FMT ;
	lv.fmt=LVCFMT_LEFT ;
	lv.pszText=_T("Path");
	ListView_InsertColumn(hwndList,2,&lv);

	SetFocus(hwndList);	
	
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);
	if (hwndCB)
		CommandBar_Show(hwndCB, TRUE);
#ifdef GAPI	
	GXOpenInput();
	// Get the Display properties
	//g_gxdp = GXGetDisplayProperties();
	g_gxk=GXGetDefaultKeys(GX_NORMALKEYS);
#endif
	return TRUE;
}

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HDC hdc;
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	int URL=0;
	TCHAR szHello[MAX_LOADSTRING];
	TCHAR* temp;
	HKEY hKey = 0;
	DWORD dwSize = 0;
	DWORD dwType = 0;
	DWORD dwTmp;
	TCHAR value[200];
//	TCHAR path[200];
//	LPTSTR t;
//	HANDLE h;
	switch (message) 
	{
		case WM_COMMAND:
			wmId    = LOWORD(wParam); 
			wmEvent = HIWORD(wParam); 
			// Parse the menu selections:
			switch (wmId)
			{
			case IDM_OPEN:
//				h=GetModuleHandle(_T("PlaylistEditor.exe"));
//				GetModuleFileName((HMODULE)h,path,200);
//				t=wcsstr(path,_T("PlaylistEditor."));
//				*t=0;
//				wcscat(path,_T("playlists\\"));
#ifdef GAPI
					if (fnGetFileName(hWnd,_T("*.pdl"), NULL,szPDLFile, 200,NULL,g_gxk.vkStart,0))
#else
					if (fnGetFileName(hWnd,_T("*.pdl"), NULL, szPDLFile, 200,NULL,VK_ESCAPE,0))
#endif
					{
						if (wcsstr(szPDLFile,_T(".pdl")))
						{
							HANDLE h=CreateFile((LPCTSTR)szPDLFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
							int size=GetFileSize(h,NULL);
							unsigned long t;
							Edited=false;
							TCHAR* temp=(TCHAR*)malloc(size);
							TCHAR* EndPos=0;
							TCHAR* BeginPos=0;
							ReadFile(h,temp,size,&t,NULL);
							CloseHandle(h);
							BeginPos=temp;
							ListView_DeleteAllItems(hwndList);
							while(BeginPos<(temp+size) &&((EndPos=wcsstr(BeginPos,_T("\r")))!=NULL))
							{
								*EndPos=0;
								AddEntry(BeginPos,-1);
								BeginPos=EndPos+2;
							}
							free(temp);
						}
					}
					break;
				case IDM_SAVE:
					{
						TCHAR temp[200];
						wcscpy(tfile,szPDLFile);
						memset(&ofn,0,sizeof(ofn));
						ofn.lStructSize	= sizeof(ofn);
						ofn.hwndOwner = hWnd;
						ofn.lpstrFile = tfile;
						ofn.nMaxFile = MAX_PATH;
						ofn.lpstrFilter = TEXT("Play List(*.pdl)\0*.pdl\0\0");	
						ofn.lpstrTitle = TEXT("Save File");
						ofn.Flags = OFN_HIDEREADONLY|OFN_PATHMUSTEXIST;
						ofn.lpstrDefExt=_T("pdl");
						if (GetSaveFileName(&ofn))
						{
							HANDLE h=CreateFile(ofn.lpstrFile,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
							if (h==INVALID_HANDLE_VALUE)
							{
								ofn.lpstrFile++;
								h=CreateFile(ofn.lpstrFile,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
							}
							wcscpy(szPDLFile,ofn.lpstrFile);
							//MessageBox(hWnd,szPDLFile,_T(""),MB_OK);
							int n=0;
							for (n=0;n<ListView_GetItemCount(hwndList);n++)
							{
								unsigned long out;
								ListView_GetItemText(hwndList,n,2,temp,200);
								wcscat(temp,_T("\r\n"));
								WriteFile(h,temp,wcslen(temp)*sizeof(TCHAR),&out,NULL);
							}
							CloseHandle(h);
							Edited=false;
						}
					}
					break;
/*				case IDM_SAVE:
					{
						TCHAR temp[200];
						memset(&ofn,0,sizeof(ofn));
						ofn.lStructSize	= sizeof(ofn);
						ofn.hwndOwner = hWnd;
						ofn.lpstrFile = szPDLFile;
						ofn.nMaxFile = MAX_PATH;
						ofn.lpstrFilter = TEXT("Play List(*.pdl)\0*.pdl\0\0");	
						ofn.lpstrTitle = TEXT("Save File");
						ofn.Flags = OFN_HIDEREADONLY; 
						if (GetSaveFileName(&ofn))
						{
							HANDLE h=CreateFile(ofn.lpstrFile,GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
							int n=0;
							for (n=0;n<ListView_GetItemCount(hwndList);n++)
							{
								unsigned long out;
								ListView_GetItemText(hwndList,n,2,temp,200);
								wcscat(temp,_T("\r\n"));
								WriteFile(h,temp,wcslen(temp)*sizeof(TCHAR),&out,NULL);
							}
							CloseHandle(h);
						}
					}
					break;*/
				case IDM_DELETE:
					{
						int n=0;
						for (n=0;n<ListView_GetItemCount(hwndList);n++)
						{
							if (ListView_GetItemState(hwndList,n,LVIS_SELECTED))
							{
								ListView_DeleteItem(hwndList,n);
							}
						}
						Edited=true;
					}
					break;
				case IDM_MOVEDOWN:
					{
						int n;
						TCHAR value[200];
						for (n=0;n<ListView_GetItemCount(hwndList);n++)
						{
							if (ListView_GetItemState(hwndList,n,LVIS_SELECTED))
							{
								if (n<ListView_GetItemCount(hwndList)-1)
								{
									ListView_GetItemText(hwndList,n,2,value,200);
									ListView_DeleteItem(hwndList,n);
									AddEntry(value,n+1);
									ListView_SetItemState(hwndList,n+1,LVIS_SELECTED|LVIS_FOCUSED,0xFFFF);
									ListView_EnsureVisible( hwndList, n+1, false );
									break;
								}
							}
						}
						Edited=true;
					}
					break;
				case IDM_MOVEUP:
					{
						int n;
						TCHAR value[200];
						for (n=0;n<ListView_GetItemCount(hwndList);n++)
						{
							if (ListView_GetItemState(hwndList,n,LVIS_SELECTED))
							{
								if (n>0)
								{
									ListView_GetItemText(hwndList,n,2,value,200);
									ListView_DeleteItem(hwndList,n);
									AddEntry(value,n-1);
									ListView_SetItemState(hwndList,n-1,LVIS_SELECTED|LVIS_FOCUSED,0xFFFF);
									ListView_EnsureVisible( hwndList, n-1, false );
									break;
								}
							}
						}
						Edited=true;
					}
					break;

				case IDM_PLAY:
				case IDM_PLAYFILE:
					{
						if (!Edited) //(szPDLFile&&(wcslen(szPDLFile)>4))
						{
							int n=0;
							int ok;
							HWND d=FindWindow(NULL,_T("PocketMVP"));
							PROCESS_INFORMATION p;
							if (d) SendMessage(d,WM_CLOSE,NULL,NULL);
							TCHAR path[200];
							TCHAR file[200];
							wcscpy(file,szPDLFile);
							for (n=0;n<ListView_GetItemCount(hwndList);n++)
							{
								if (ListView_GetItemState(hwndList,n,LVIS_SELECTED))
								{
									TCHAR temp[10];
									wcscat(file,_T(" "));
									_itow(n,temp,10);
									wcscat(file,temp);
								}
							}

							HANDLE h=GetModuleHandle(_T("PlayListEditor.exe"));
							GetModuleFileName((HMODULE)h,path,200);
							LPTSTR t=wcsstr(path,_T("PlaylistEditor"));
							*t=0;
							wcscat(path,_T("PocketMVP.exe"));
							ok=CreateProcess(path,file,NULL,NULL,NULL,0,NULL,NULL,NULL,&p);
						}
						else
						{
							MessageBox(hWnd,_T("You have unsaved changes."),_T("Cannot Play"),MB_OK);
						}
					}
					break;
				case IDM_ADD_URL:
					URL=1;
				case IDM_ADD:
					wcscpy(value,_T("*.divx,*.avi"));
					if ( ERROR_SUCCESS == RegOpenKeyEx( HKEY_LOCAL_MACHINE, REG_BASE_FMT, 0, 0, &hKey ) )
					{
						dwTmp = 0;
						dwSize =sizeof(value);
						RegQueryValueEx( hKey, _T("SupportedExtensions"), 0, &dwType, ( LPBYTE )value, &dwSize );
					}
#ifdef GAPI
					if (fnGetFileName(hWnd,value, NULL,szFile, 200,&temp,g_gxk.vkStart,URL))
#else
					if (fnGetFileName(hWnd,value, NULL,szFile, 200,&temp,VK_ESCAPE,URL))
#endif
					{
							TCHAR* EndPos=0;
							TCHAR* BeginPos=0;
							BeginPos=temp;
							Edited=true;
							while(((EndPos=wcsstr(BeginPos,_T("\r")))!=NULL))
							{
								*EndPos=0;
								AddEntry(BeginPos,-1);
								BeginPos=EndPos+2;
							}
					}
					break;

				case IDM_FILE_EXIT:
				   DestroyWindow(hWnd);
				   break;
				default:
				   return DefWindowProc(hWnd, message, wParam, lParam);
			}
			break;
		case WM_CREATE:
			{
#if (_WIN32_WCE >= 300 && !defined(HPC))
			//Create the PocketPC compatible menubar.
			HANDLE ha=LoadLibrary(_T("aygshell.dll"));
			if (ha!=NULL)
			{
				aygshell_SHCreateMenuBar=(paygshell_SHCreateMenuBar)GetProcAddress((HINSTANCE)ha,_T("SHCreateMenuBar"));
			}
			SHMENUBARINFO sMbi;
			memset( &sMbi, 0, sizeof ( SHMENUBARINFO ) );
			sMbi.cbSize = sizeof( sMbi );
			sMbi.hwndParent = hWnd;
			sMbi.dwFlags = 0; //SHCMBF_SHOWSIPBUTTON;
			sMbi.nToolBarId = IDR_MENUBAR1;
			sMbi.hInstRes = hInst;
			sMbi.nBmpId = 0;
			sMbi.cBmpImages = 0;

			if ( aygshell_SHCreateMenuBar( &sMbi ) )
			{
				hwndCB = sMbi.hwndMB;
			}
#else
			hwndCB = CommandBar_Create(hInst, hWnd, 1);			
			CommandBar_InsertMenubar(hwndCB, hInst, IDM_MENU, 0);
#endif
			TBBUTTON but;
			but.fsState=TBSTATE_ENABLED   ;
			but.fsStyle=TBSTYLE_BUTTON   ;
			but.iBitmap=0;
			but.iString=0;
			but.idCommand=IDM_OPEN;
			CommandBar_AddBitmap(hwndCB,hInst,IDB_BUTTONS,8,16,16);
			CommandBar_AddToolTips(hwndCB,9,ToolTips);
			CommandBar_InsertButton(hwndCB,1, &but);
			but.iBitmap=1;
			but.idCommand=IDM_SAVE;
			CommandBar_InsertButton(hwndCB,2, &but);
			but.iBitmap=2;
			but.idCommand=IDM_ADD;
			CommandBar_InsertButton(hwndCB,3, &but);
			but.iBitmap=3;
			but.idCommand=IDM_ADD_URL;
			CommandBar_InsertButton(hwndCB,4, &but);
			but.iBitmap=4;
			but.idCommand=IDM_DELETE;
			CommandBar_InsertButton(hwndCB,5, &but);
			but.iBitmap=5;
			but.idCommand=IDM_PLAY;
			CommandBar_InsertButton(hwndCB,6, &but);
			but.iBitmap=6;
			but.idCommand=IDM_MOVEUP;
			CommandBar_InsertButton(hwndCB,7, &but);
			but.iBitmap=7;
			but.idCommand=IDM_MOVEDOWN;
			CommandBar_InsertButton(hwndCB,8, &but);
#if ( defined(HPC))
			CommandBar_AddAdornments(hwndCB,NULL,NULL);
#endif
			}
			break;
		case WM_PAINT:
			hdc = BeginPaint(hWnd, &ps);
			EndPaint(hWnd, &ps);
			break;
		case WM_DESTROY:
			CommandBar_Destroy(hwndCB);
			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

