/* --- DELETEPLAYLISTENTRY.CPP ---
/  
/ Written by Phil Himsworth, 2001-2002.
/
/*/

#include <windows.h>

#include "types.h"
#include "main.h"
#include "html.h"
#include "plugin.h"
#include "wamessage.h"

// --------------------------------------------------------------------------------
// Delete a playlist entry by manipulating the playlist file.
// No longer used; replaced by DeletePlaylistEntry2 (below) which is much shorter and easier!
int DeletePlaylistEntry(int track)
{
	// Get current position and save playlist to winamp.m3u
	int plcount = SendMessage(WAwnd(),WM_USER,0,WAU_PLCOUNT);
	int plpos = SendMessage(WAwnd(),WM_USER,0,WAU_PLSAVE);


	// Find winamp.m3u; it's in the same dir as exe of current process. 
	DWORD wapid = GetWindowThreadProcessId(WAwnd(),NULL);
	HMODULE hMod = (HMODULE)OpenProcess(PROCESS_ALL_ACCESS,false,wapid);

	char playlistfile[MAX_PATH], *p;
	GetModuleFileName(hMod,playlistfile,sizeof(playlistfile));
	CloseHandle(hMod);

	// Make \path\winamp.exe into \path\winamp.m3u
	p=playlistfile+lstrlen(playlistfile);
	while (p >= playlistfile && *p != '\\') p--;
	if (++p >= playlistfile) *p = 0;
	lstrcat(playlistfile,"winamp.m3u");


	/* Right then, that's the playlist file extracted and found.
	  - read playlist into memory - linked list
	  - scan through list writing back to playlist file
		 - don't write back track to delete
	  - reload playlist. As easy as that...
	*/


	HANDLE hFile = CreateFile(	playlistfile,
								GENERIC_READ,
								FILE_SHARE_READ,
								NULL,
								OPEN_EXISTING,
								FILE_FLAG_SEQUENTIAL_SCAN,
								NULL);

	if (hFile == INVALID_HANDLE_VALUE)
		return DPE_NOREAD;

	// Put entire file into a char array
	DWORD dwSize = GetFileSize(hFile, NULL);
	char * cplaylist = new char[dwSize];
	DWORD read;
	ReadFile(hFile,cplaylist,dwSize,&read,NULL);
	CloseHandle(hFile);

	// playlist file is now in cplaylist; scan through and put in a 'playlist' structure


	char * chptr = cplaylist;
	char temp[MAX_PATH];

	playlistitem * startitem = NULL;
	playlistitem * currentitem = startitem;

	for (int i=1;i<=plcount;i++)
	{

		playlistitem * newitem = new playlistitem;
		newitem->next = NULL;
		newitem->number = i;

		// skip '#EXTINF:'
		chptr = GetDelimitedString(chptr,':',temp,MAX_PATH);
		chptr++;

		// get time
		chptr = GetDelimitedString(chptr,',',newitem->time,10);
		chptr++;
		// get title
		chptr = GetDelimitedString(chptr,'\r',newitem->name,MAX_PATH);
		chptr++;
		chptr++;

		// get path
		chptr = GetDelimitedString(chptr,'\r',newitem->path,MAX_PATH);

		if (startitem == NULL)
		{
			startitem = newitem;
			currentitem = newitem;
		}
		else
		{
			currentitem->next = newitem;
			currentitem = newitem;
		}
	}

	// hopefully the list is complete here.

	// Open winamp.m3u for writing
	hFile = CreateFile(	playlistfile,
								GENERIC_WRITE,
								0,
								NULL,
								CREATE_ALWAYS,
								FILE_FLAG_SEQUENTIAL_SCAN,
								NULL);

	if (hFile == INVALID_HANDLE_VALUE)
	{
		FreePlaylist(startitem);
		return DPE_NOWRITE;
	}

	// Write it back into cplaylist. It'll be shorter, obviously, so it'll fit
	wsprintf(cplaylist,"#EXTM3U\r\n");
	currentitem = startitem;
	while(currentitem != NULL)
	{
		if (currentitem->number != track)
		{
			wsprintf(temp,"#EXTINF:%s,%s\r\n%s\r\n",currentitem->time,currentitem->name,currentitem->path);
			lstrcat(cplaylist,temp);
		}
		currentitem = currentitem->next;
	}

	// Write playlist to file
	DWORD written;
	WriteFile(hFile,cplaylist,lstrlen(cplaylist),&written,NULL);
	CloseHandle(hFile);
	delete cplaylist;

	// free memory of linked list
	FreePlaylist(startitem);

	// clear current playlist and reload it
	SendMessage(WAwnd(),WM_USER,0,WAU_CLEARPLIST);

	int pathlen = lstrlen(playlistfile);
	COPYDATASTRUCT cds;
	cds.dwData = IPC_PLAYFILE;
	cds.lpData = (void *)&playlistfile;
	cds.cbData = pathlen+1;
	SendMessage(WAwnd(),WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cds);


	// return to old position in list
	if (plpos >= track)
		plpos--;
	SendMessage(WAwnd(),WM_USER,plpos,WAU_SETPLPOS);

	return DPE_OK;

}

// --------------------------------------------------------------------------------
// Delete linked list after it's done with
void FreePlaylist(playlistitem * startitem)
{
	playlistitem * current = startitem;

	while(current != NULL)
	{
		startitem = current->next;
		delete current;
		current = startitem;
	}
}

// --------------------------------------------------------------------------------
// Delete using Playlist window messages
int DeletePlaylistEntry2(connection * conn, int track)
{
	HWND PLwnd = FindWindow("Winamp PE",NULL);
	if (!PLwnd)
	{
		LPVOID lpMsgBuf;
		FormatMessage( 
			FORMAT_MESSAGE_ALLOCATE_BUFFER | 
			FORMAT_MESSAGE_FROM_SYSTEM | 
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			GetLastError(),
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			(LPTSTR) &lpMsgBuf,
			0,
			NULL 
		);
		// Process any inserts in lpMsgBuf.
		// ...
		// Display the string.
		MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
		// Free the buffer.
		LocalFree( lpMsgBuf );
	}


	SendMessage(PLwnd,WM_USER,104,track);

	OpenHTTPHeader(conn,"text/html",0,NULL);
	if (conn->http.reqID == RID_HEAD)
		return ST_CLOSE;

	OpenHtmlHeader(conn);
	char refreshto[MAX_PATH];
	if (!GetArgValue(conn,"refresh",refreshto,10))
		wsprintf(refreshto,"/list");

	RefreshHeader(conn,refreshto);
	Style(conn);
	CloseHeader(conn);
	OpenPageBody(conn);
	prints(conn,"<p>Track");
	printsi(conn,track);
	prints(conn," deleted</p>");

	return ST_CLOSEBODY;

}