#include "EditYPList.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "WimpLib:Desktop.h"
#include "WimpLib:Display.h"
#include "WimpLib:Exception.h"
#include "WimpLib:Hourglass.h"
#include "WimpLib:mem.h"
#include "WimpLib:Menu.h"
#include "WimpLib:Message.h"
#include "WimpLib:Slider.h"
#include "WimpLib:Task.h"
#include "WimpLib:Template.h"
#include "WimpLib:Utils.h"
#include "WimpLib:Window.h"
#include "WimpLib:WStringList.h"

#include "DigitalCD.h"
#include "Options.h"
#include "FileList.h"
#include "DocEvents.h"
#include "UserEvents.h"

#define Prop_Url         0x001
#define Prop_Title       0x002
#define Prop_Info        0x004
#define Prop_Autoload    0x008
#define Prop_AllProps    0x00f
#define Prop_SingleObject    0x80000000
#define Prop_RefreshContents 0x40000000
#define Prop_RefreshState    0x20000000

typedef unsigned int Props;

#define EIcon_ColorMask   0xf0000000
#define EIcon_ColorNormal 0x00000000
#define EIcon_ColorDiffer 0x20000000

#define EIcon_FillColorMask   0xf0000020
#define EIcon_FillColorNormal 0x10000000
#define EIcon_FillColorDiffer 0x20000020

#define EditFlags_Create   0x01
#define EditFlags_Updating 0x02 // We are fiddling with the tracks, ignore DocEvents

typedef struct
{
	HWind             m_wnd;
	List*             m_pTracks;
	const FLTrack*    m_pRefTrack;
	void*             m_pView;
	Props             m_AllowedProps;
	Props             m_DifferingProps;
	Props             m_ModifiedProps;
	unsigned int      m_flags;
	struct
	{
		const char*   url;
		const char*   title;
		const char*   info;
		bool          autoload;
	} m_ref;
	struct
	{
		bool          autoload;
	} m_new;
} EditYPList;

static EditYPList TheEditYPList = {HWind_None};

#define Icon_Set          0
#define Icon_Cancel       1
#define Icon_Url          2
#define Icon_Title        4
#define Icon_Info         6
#define Icon_Autoload     7

/**
 * Sets the reference track to use for building the properties.
 * If the reference track is not contained in the list of edited tracks
 * the first one from the list is used as reference.
 *
 * @param  pRef  Pointer to the reference track to use.
 */
static void EditYPList_SetRefTrack(EditYPList* This, const FLTrack* pRef)
{
	This->m_pRefTrack = NULL;

	if (pRef)
	{
		if (List_Find(This->m_pTracks, 0, pRef) != -1)
			This->m_pRefTrack = pRef;
	}

	if (!This->m_pRefTrack && (List_Count(This->m_pTracks) > 0))
		This->m_pRefTrack = List_Get(This->m_pTracks, 0);
}

/**
 * Refreshes the state of buttons
 */
static void EditYPList_RefreshButtons(EditYPList* This)
{
	bool b;

	b = !This->m_ModifiedProps;
	if (This->m_flags & EditFlags_Create) b = false;

	Icon_SetDimmed(This->m_wnd, Icon_Set, b);
}

/**
 * Refreshes the window contents for given properties
 *
 * @param  props  bitlist of properties to refresh
 *                + Prop_RefreshContents is the properties values are to be updated
 *                + Prop_RefreshState is the properties common/allowed status are to be updated.
 */
static void EditYPList_Refresh(EditYPList* This, Props props)
{
	bool b;

	if (props & Prop_Url)
	{
		b = (This->m_AllowedProps & Prop_Url) == 0;

		if (props & Prop_RefreshContents)
			Icon_SetData(This->m_wnd, Icon_Url, This->m_ref.url);

		if (props & Prop_RefreshState)
		{
			Icon_SetDimmed(This->m_wnd, Icon_Url, b);
			Icon_SetState(This->m_wnd, Icon_Url
			             , (This->m_DifferingProps & Prop_Url)
			             ? EIcon_ColorDiffer : EIcon_ColorNormal, EIcon_ColorMask);
		}
	}

	if (props & Prop_Title)
	{
		b = (This->m_AllowedProps & Prop_Title) == 0;

		if (props & Prop_RefreshContents)
			Icon_SetData(This->m_wnd, Icon_Title, This->m_ref.title);

		if (props & Prop_RefreshState)
		{
			Icon_SetDimmed(This->m_wnd, Icon_Title - 1, b);
			Icon_SetDimmed(This->m_wnd, Icon_Title, b);
			Icon_SetState(This->m_wnd, Icon_Title
			             , (This->m_DifferingProps & Prop_Title)
			             ? EIcon_ColorDiffer: EIcon_ColorNormal, EIcon_ColorMask);
		}
	}

	if (props & Prop_Info)
	{
		b = (This->m_AllowedProps & Prop_Info) == 0;

		if (props & Prop_RefreshContents)
			Icon_SetData(This->m_wnd, Icon_Info, This->m_ref.info);

		if (props & Prop_RefreshState)
		{
			Icon_SetDimmed(This->m_wnd,Icon_Info - 1, b);
			Icon_SetDimmed(This->m_wnd,Icon_Info, b);
			Icon_SetState(This->m_wnd, Icon_Info
			             , (This->m_DifferingProps & Prop_Info)
			             ? EIcon_ColorDiffer: EIcon_ColorNormal, EIcon_ColorMask);
		}
	}

	if (props & Prop_Autoload)
	{
		b = (This->m_AllowedProps & Prop_Autoload) == 0;

		if (props & Prop_RefreshContents)
			Icon_SetHighlight(This->m_wnd, Icon_Autoload, This->m_new.autoload);

		if (props & Prop_RefreshState)
		{
			Icon_SetDimmed(This->m_wnd,Icon_Autoload, b);
			Icon_SetState(This->m_wnd, Icon_Autoload
			             , (This->m_DifferingProps & Prop_Autoload)
			             ? EIcon_FillColorDiffer: EIcon_FillColorNormal, EIcon_FillColorMask);
		}
	}
}

/**
 * Builds the properties initial values and allowed status.
 */

static void EditYPList_BuildProperties(EditYPList* This)
{
	const FLTrack* pTrack;
	bool b;

	This->m_AllowedProps = Prop_AllProps;
	This->m_ModifiedProps = 0;

	if (List_Count(This->m_pTracks) > 1)
		This->m_AllowedProps &= ~Prop_Url;
	else
		This->m_AllowedProps |= Prop_SingleObject;

	pTrack = This->m_pRefTrack;

	b = (This->m_AllowedProps & Prop_Url) == 0;
	throw_mem_setstring(&This->m_ref.url, b ? NULL : FLTrack_GetFilename(pTrack));

	b = (This->m_AllowedProps & Prop_Title) == 0;
	throw_mem_setstring(&This->m_ref.title, b ? NULL : FLTrack_GetMetaString(pTrack, EMetaId_StreamTitle));

	b = (This->m_AllowedProps & Prop_Info) == 0;
	throw_mem_setstring(&This->m_ref.info, b ? NULL : FLTrack_GetInfo(pTrack));

	b = (This->m_AllowedProps & Prop_Autoload) == 0;
	This->m_new.autoload = This->m_ref.autoload
		= b ? false : ((FLTrack_GetFlags(pTrack) & FLTrack_DoNotAutoload) == 0);

	EditYPList_Refresh(This, Prop_RefreshContents | Prop_AllProps);

	EditYPList_RefreshButtons(This);
}

/**
 * Takes note of the properties for which the values are not identical in all tracks.
 */

static void EditYPList_BuildCommonStatus(EditYPList* This)
{
	if (This->m_AllowedProps & Prop_SingleObject)
	{
		This->m_DifferingProps = 0;
	}
	else
	{
		ListNode* pNode;
		const FLTrack* pTrack;
		Props commons = This->m_AllowedProps;


		// Check all allowed/non-modified properties to see
		// if their values correspond to the initial values.
		pNode = NULL;

		while (commons && ((pNode = List_GetSuccessor(This->m_pTracks, pNode)) != NULL))
		{
			pTrack = List_GetNodeData(This->m_pTracks, pNode);

			if (commons & Prop_Url)
			{
				if (strcmp(nvl(This->m_ref.url), FLTrack_GetFilename(pTrack)))
					commons &= ~Prop_Url;
			}

			if (commons & Prop_Title)
			{
				if (strcmp(nvl(This->m_ref.title), FLTrack_GetMetaString(pTrack, EMetaId_StreamTitle)))
					commons &= ~Prop_Title;
			}

			if (commons & Prop_Info)
			{
				if (strcmp(nvl(This->m_ref.info), FLTrack_GetInfo(pTrack)))
					commons &= ~Prop_Info;
			}

			if (commons & Prop_Autoload)
			{
				bool b = ((FLTrack_GetFlags(pTrack) & FLTrack_DoNotAutoload) == 0);
				if (This->m_ref.autoload != b)
					commons &= ~Prop_Autoload;
			}
		}

		This->m_DifferingProps = This->m_AllowedProps & ~commons;
	}

	EditYPList_Refresh(This, Prop_RefreshState | Prop_AllProps);
}

/**
 * Takes note of the properties which were modified.
 */

static void EditYPList_CheckChanges(EditYPList* This, Props props)
{
	Props modifs = 0;
	Props updated;

	props &= This->m_AllowedProps;

	// Check values with references
	if (props & Prop_Url)
	{
		if (strcmp(nvl(This->m_ref.url), Icon_GetData(This->m_wnd, Icon_Url)))
			modifs |= Prop_Url;
	}

	if (props & Prop_Title)
	{
		if (strcmp(nvl(This->m_ref.title), Icon_GetData(This->m_wnd, Icon_Title)))
			modifs |= Prop_Title;
	}

	if (props & Prop_Info)
	{
		if (strcmp(nvl(This->m_ref.info), Icon_GetData(This->m_wnd, Icon_Info)))
			modifs |= Prop_Info;
	}

	if (props & Prop_Autoload)
	{
		This->m_new.autoload = (Icon_GetState(This->m_wnd, Icon_Autoload, EIcon_Selected) != 0);
		if (This->m_ref.autoload != This->m_new.autoload)
			modifs |= Prop_Autoload;
	}

	// Any change compared to old status?
	updated = (modifs ^ This->m_ModifiedProps) & props;

	if (This->m_AllowedProps & Prop_SingleObject)
	{
		// reflect even reversion to original values
		if (updated)
		{
			This->m_ModifiedProps ^= updated;

			EditYPList_RefreshButtons(This);
		}
	}
	else
	{
		// reflect new changes but there is no reversion
		// to original value since any change affected old values
		updated &= modifs;

		if (updated)
		{
			This->m_ModifiedProps |= updated;
			This->m_DifferingProps &= ~updated;
			EditYPList_Refresh(This, Prop_RefreshState | updated);

			EditYPList_RefreshButtons(This);
		}
	}
}

static void EditYPList_ClearTracks(EditYPList* This)
{
	This->m_flags |= EditFlags_Updating;

	try
	{
		if (This->m_flags & EditFlags_Create)
		{
			ListNode* pNode;
			FLTrack* pTrack;

			pNode = NULL;

			while ((pNode = List_GetSuccessor(This->m_pTracks, pNode)) != NULL)
			{
				pTrack = List_GetNodeData(This->m_pTracks, pNode);
				Delete_FLTrack(pTrack);
			}
		}
	}
	catch
	{
		App_ReportException();
	}
	catch_end

	List_Clear(This->m_pTracks);

	This->m_flags &= ~EditFlags_Updating;
}

static bool EditYPList_OnOk(EditYPList* This)
{
	ListNode* pNode;
	FileList* pOwner = NULL;
	const char* string;
	int i = 0;
	int max = List_Count(This->m_pTracks);

	// Checks
	if (This->m_AllowedProps & Prop_Url)
	{
		String_StripBlanks(Icon_GetData(This->m_wnd, Icon_Url));

		if (!*Icon_GetData(This->m_wnd, Icon_Url))
		{
			App_ReportError("DSErr9");
			return false;
		}
	}

	// Set
	bool off = !WLib_Hourglass_IsOn();
	if (off) WLib_Hourglass_On();
	pNode = NULL;

	This->m_flags |= EditFlags_Updating;

	try
	{
		while ((pNode = List_GetSuccessor(This->m_pTracks, pNode)) != NULL)
		{
			FLTrack* pTrack = List_GetNodeData(This->m_pTracks, pNode);

			WLib_Hourglass_Percentage((100 * i++)/max);

			if (pOwner != FLTrack_GetOwner(pTrack))
			{
				if (pOwner != NULL) FileList_EndUpdate(pOwner, false, false);

				pOwner = FLTrack_GetOwner(pTrack);
				if (pOwner != NULL) FileList_StartUpdate(pOwner);
			}

			FileList* pList = NULL;

			bool bAutoModSubList = false;
			bool bModSubList = false;
			bool bModList = false;
			bool bModTrack = false;

			// must set url for create in case it starts download directly
			if (This->m_ModifiedProps & Prop_Url)
				bModList |= FLTrack_SetFilename(pTrack, Icon_GetData(This->m_wnd, Icon_Url), false);

			if (This->m_flags & EditFlags_Create)
			{
				try
				{
					pOwner = (FileList*) View_GetDocument(This->m_pView);
					int pos = throw_FileList_InsertTrackAt(pOwner, -1, pTrack);
					FileList_Show(pOwner, pos);
					pList = throw_New_FileList_FromTrack(pTrack);
					FileList_Show(pList, -1);
				}
				catch
				{
					App_ReportException();
				}
				catch_end
			}
			else
			{
				pList = FLTrack_GetSubList(pTrack);
			}

			if (This->m_ModifiedProps & Prop_Title)
			{
				string = Icon_GetData(This->m_wnd, Icon_Title);
				bModTrack |= FLTrack_SetMetaText(pTrack, EMetaId_StreamTitle, EMetaOrigin_User, string);
				if (pList) bAutoModSubList |= FileList_SetTitle(pList, string);
			}

			if (This->m_ModifiedProps & Prop_Info)
			{
				string = Icon_GetData(This->m_wnd, Icon_Info);
				bModTrack |= FLTrack_SetInfo(pTrack, string);
				if (pList) bAutoModSubList |= FileList_SetInfo(pList, string);
			}

			if (This->m_ModifiedProps & Prop_Autoload)
				bModTrack |= FLTrack_SetFlags(pTrack, This->m_new.autoload ? 0 : FLTrack_DoNotAutoload, FLTrack_DoNotAutoload);

			if (pList)
			{
				if (bAutoModSubList) FileList_SetAutoModifiedFlag(pList);
				if (bModSubList) FileList_SetModifiedFlag(pList, true);
			}

			FLTrack_RefreshViews(pTrack, This, bModTrack, bModList);
		}

		if (pOwner != NULL) FileList_EndUpdate(pOwner, false, false);
	}
	catch
	{
		App_ReportException();
	}
	catch_end

	This->m_flags &= ~EditFlags_Updating;

	if (off) WLib_Hourglass_Off();

	// Once here new modications are updates
	This->m_flags &= ~EditFlags_Create;

	// Reset settings
	EditYPList_BuildProperties(This);
	EditYPList_BuildCommonStatus(This);

	return true;
}

static void EditYPList_OnCancel(EditYPList* This)
{
	// Reset settings
	EditYPList_BuildProperties(This);
	EditYPList_BuildCommonStatus(This);
}

static EListenerAction EditYPList_Listener(void* handle, const Event* e)
{
	EditYPList* This = handle;

	switch(e->Type)
	{
		case EEvent_OptionParentalLock:
		{
			if (Options()->Player.bParentalLock)
			{
				EditYPList_OnCancel(This);
				Window_Close(This->m_wnd);
			}
		}
		break;
	}

	return EListenerAction_ContinueEvent;
}

static EListenerAction EditYPList_EventHandler(void* handle, const Event* e)
{
	EditYPList* This = handle;

	switch(e->Type)
	{
		case EEvent_Mouse:
		{
			const Mouse* m = e->pData;

			if (m->but & EBut_Menu)
				return EListenerAction_StopEvent;

			switch(m->i)
			{
				case Icon_Cancel:
				{
					EditYPList_OnCancel(This);
					if (m->but & EBut_Select)
						Window_Close(This->m_wnd);
				}
				break;
				case Icon_Set:
				{
					if (EditYPList_OnOk(This)
					&&  (m->but & EBut_Select))
						Window_Close(This->m_wnd);
				}
				break;
				case Icon_Autoload:
				{
					EditYPList_CheckChanges(This, Prop_Autoload);
				}
				break;
			}

			return EListenerAction_StopEvent;
		}
		break;
		case EEvent_Key:
		{
			const Event_Key* pkey = e->pData;

			switch(pkey->code)
			{
				case 0x1b: // Esc
				{
					EditYPList_OnCancel(This);
					Window_Close(This->m_wnd);
					return EListenerAction_StopEvent;
				}
				break;
				case 0x0d: // Return
				{
					if (pkey->caret.pos.i == Icon_Info)
					{
						if (EditYPList_OnOk(This))
							Window_Close(This->m_wnd);
					}
					return EListenerAction_StopEvent;
				}
				break;
				case 0x181: // F1
				{
					App_StrongHelp("Playlist_PropYPs");
					return EListenerAction_StopEvent;
				}
				break;
				default:
				{
					switch (pkey->caret.pos.i)
					{
						case Icon_Url:
						{
							EditYPList_CheckChanges(This, Prop_Url);
						}
						break;
						case Icon_Title:
						{
							EditYPList_CheckChanges(This, Prop_Title);
						}
						break;
						case Icon_Info:
						{
							EditYPList_CheckChanges(This, Prop_Info);
						}
						break;
					}
					break;
				}
			}
		}
		break;
	}

	return EListenerAction_ContinueEvent;
}

static EListenerAction EditYPList_OnDocEvent(void* pListener, const Event* pEvent)
{
	EditYPList* This = pListener;
	const DocEvent* pe = pEvent->pData;

	if ((This->m_wnd == HWind_None)
	||  (This->m_flags & EditFlags_Updating))
		return EListenerAction_ContinueEvent;

	switch(pe->event)
	{
		case EDocEvent_RemoveElement:
		case EDocEvent_UpdateElement:
		{
			int pos = List_Find(This->m_pTracks, 0, pe->pElement);

			if (pos != -1)
			{
				EditYPList_OnCancel(This);
				EditYPList_ClearTracks(This);
				Window_Close(This->m_wnd);
			}
		}
		break;
	}

	return EListenerAction_ContinueEvent;
}

void EditYPList_EditNew(void* pView)
{
	EditYPList_Edit(pView, NULL, NULL);
}

void EditYPList_Edit(void* pView, List* pList, const FLTrack* pRef)
{
	EditYPList* This = &TheEditYPList;

	if (Options()->Player.bParentalLock)
		return;

	if (This->m_wnd == HWind_None)
	{
		memset(This, 0, sizeof(*This));
		This->m_wnd = HWind_None;

		try
		{
			This->m_pTracks = New_List();

			This->m_wnd = throw_Window_CreateFrom("PropYP", "YPropH");

			throw_Window_RegisterEventHandler(This->m_wnd, EditYPList_EventHandler, This, false);
			throw_Task_AddListener(EEvent_OptionParentalLock, EditYPList_Listener, This, false);

			throw_DocEvents_AddListener(NULL, This, EditYPList_OnDocEvent);
		}
		catch
		{
			EditYPList_NotEdit();
			App_ReportException();
			return;
		}
		catch_end
	}

	This->m_pView = pView;

	EditYPList_ClearTracks(This);

	try
	{
		if (pList && List_Count(pList))
		{
			ListNode* pNode;
			FLTrack* pTrack;

			pNode = NULL;

			while ((pNode = List_GetSuccessor(pList, pNode)) != NULL)
			{
				pTrack = List_GetNodeData(pList, pNode);

				List_InsertBefore(This->m_pTracks, NULL, pTrack);
			}

			This->m_flags &= ~EditFlags_Create;
		}
		else if (!pList && pView)
		{
			// Creation mode
			FileList* pOwner = (FileList*) View_GetDocument(pView);
			FLTrack* pTrack = throw_New_FLTrack
								( pOwner
								, FLTrack_IsUrl|FLTrack_IsPlaylist|FLTrack_DoNotAutoload
								, "http://"
								);

			List_InsertBefore(This->m_pTracks, NULL, pTrack);

			This->m_flags |= EditFlags_Create;
		}
	}
	catch
	{
		App_ReportException();
		EditYPList_ClearTracks(This);
	}
	catch_end

	EditYPList_SetRefTrack(This, pRef);

	if (!List_Count(This->m_pTracks))
	{
		Window_Close(This->m_wnd);
	}
	else
	{
		EditYPList_BuildProperties(This);
		EditYPList_BuildCommonStatus(This);

		Window_Open(This->m_wnd);
		Icon_SetFocus(This->m_wnd, Icon_Title, -1);
	}
}

void EditYPList_NotEdit(void)
{
	EditYPList* This = &TheEditYPList;

	if (This->m_pTracks)
	{
		EditYPList_ClearTracks(This);
		Delete_List(This->m_pTracks);
	}

	if (This->m_wnd != HWind_None)
	{
		DocEvents_RemoveListener(NULL, This, EditYPList_OnDocEvent);
		Task_RemoveListener(EEvent_OptionParentalLock, EditYPList_Listener, This);
		Window_DeRegisterEventHandler(This->m_wnd, EditYPList_EventHandler, This);
		Window_Delete(This->m_wnd);
	}

	mem_free(This->m_ref.url);
	mem_free(This->m_ref.title);
	mem_free(This->m_ref.info);

	memset(This, 0, sizeof(*This));
	This->m_wnd = HWind_None;
}
