#include "EditCDTrack.h"

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

#include "WimpLib:Caret.h"
#include "WimpLib:Desktop.h"
#include "WimpLib:Display.h"
#include "WimpLib:Exception.h"
#include "WimpLib:File.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:Window.h"
#include "WimpLib:WList.h"
#include "WimpLib:WStringList.h"

#include "CDDesc.h"
#include "CDTrack.h"
#include "DigitalCD.h"
#include "Options.h"
#include "Setup.h"
#include "DocEvents.h"
#include "UserEvents.h"

#define Prop_Track       0x00001
#define Prop_Title       0x00002
#define Prop_Artist      0x00004
#define Prop_Collective  0x00008
#define Prop_AllProps        0x0000000F
#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_Updating 0x02 // We are fiddling with the tracks, ignore DocEvents

typedef struct
{
	HWind             m_wnd;
	List*             m_pTracks;
	const CDTrack*    m_pRefTrack;
	Props             m_AllowedProps;
	Props             m_DifferingProps;
	Props             m_ModifiedProps;
	unsigned int      m_flags;
	struct
	{
		const char*   title;
		const char*   artist;
		const char*   collective;
	} m_ref;
	WStringList*      m_pWCollectiveList;
	WStringList*      m_pWArtistList;
} EditCDTrack;

static EditCDTrack TheEditCDTrack = {HWind_None};

#define Icon_Set          0
#define Icon_Cancel       1

#define Icon_Track        3
#define Icon_CD           5
#define Icon_Title        7
#define Icon_Artist       9
#define Icon_Collective  11

/**
 * 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 EditCDTrack_SetRefTrack(EditCDTrack* This, const CDTrack* 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 EditCDTrack_RefreshButtons(EditCDTrack* This)
{
	bool b;

	b = !This->m_ModifiedProps;

	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 EditCDTrack_Refresh(EditCDTrack* This, Props props)
{
	bool b;

	if (props & Prop_Track)
	{
		if (This->m_AllowedProps & Prop_Track)
		{
			Icon_Printf(This->m_wnd, Icon_Track, "%02d", CDTrack_GetOrder(This->m_pRefTrack));
			Icon_SetData(This->m_wnd, Icon_CD, CDDesc_GetLabel(CDTrack_GetCDDesc(This->m_pRefTrack)));
		}
		else
		{
			Icon_SetData(This->m_wnd, Icon_Track, NULL);
			Icon_SetData(This->m_wnd, Icon_CD, NULL);
		}

	}

	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_Artist)
	{
		b = (This->m_AllowedProps & Prop_Artist) == 0;

		if (props & Prop_RefreshContents)
			WStringList_SetIconData(This->m_pWArtistList, This->m_ref.artist);

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

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

		if (props & Prop_RefreshContents)
			WStringList_SetIconData(This->m_pWCollectiveList, This->m_ref.collective);

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

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

static void EditCDTrack_BuildProperties(EditCDTrack* This)
{
	const CDTrack* pTrack;
	bool b;

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

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

	pTrack = This->m_pRefTrack;

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

	b = (This->m_AllowedProps & Prop_Artist) == 0;
	throw_mem_setstring(&This->m_ref.artist, b ? NULL : CDTrack_GetMetaString(pTrack, EMetaId_StreamArtist));

	b = (This->m_AllowedProps & Prop_Collective) == 0;
	throw_mem_setstring(&This->m_ref.collective, b ? NULL : CDTrack_GetMetaString(pTrack, EMetaId_StreamCollective));

	EditCDTrack_Refresh(This, Prop_RefreshContents | Prop_AllProps);

	EditCDTrack_RefreshButtons(This);
}

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

static void EditCDTrack_BuildCommonStatus(EditCDTrack* This)
{
	if (This->m_AllowedProps & Prop_SingleObject)
	{
		This->m_DifferingProps = 0;
	}
	else
	{
		ListNode* pNode;
		const CDTrack* 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_Title)
			{
				if (strcmp(nvl(This->m_ref.title), CDTrack_GetMetaString(pTrack, EMetaId_StreamTitle)))
					commons &= ~Prop_Title;
			}

			if (commons & Prop_Artist)
			{
				if (strcmp(nvl(This->m_ref.artist), CDTrack_GetMetaString(pTrack, EMetaId_StreamArtist)))
					commons &= ~Prop_Artist;
			}

			if (commons & Prop_Collective)
			{
				if (strcmp(nvl(This->m_ref.collective), CDTrack_GetMetaString(pTrack, EMetaId_StreamCollective)))
					commons &= ~Prop_Collective;
			}
		}

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

	EditCDTrack_Refresh(This, Prop_RefreshState | Prop_AllProps);
}

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

static void EditCDTrack_CheckChanges(EditCDTrack* This, Props props)
{
	Props modifs = 0;
	Props updated;

	props &= This->m_AllowedProps;

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

	if (props & Prop_Artist)
	{
		if (strcmp(nvl(This->m_ref.artist), Icon_GetData(This->m_wnd, Icon_Artist)))
			modifs |= Prop_Artist;
	}

	if (props & Prop_Collective)
	{
		if (strcmp(nvl(This->m_ref.collective), Icon_GetData(This->m_wnd, Icon_Collective)))
			modifs |= Prop_Collective;
	}

	// 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;

			EditCDTrack_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;
			EditCDTrack_Refresh(This, Prop_RefreshState | updated);

			EditCDTrack_RefreshButtons(This);
		}
	}
}

static void EditCDTrack_ClearTracks(EditCDTrack* This)
{
	This->m_flags |= EditFlags_Updating;

	List_Clear(This->m_pTracks);

	This->m_flags &= ~EditFlags_Updating;
}

static bool EditCDTrack_OnOk(EditCDTrack* This)
{
	ListNode* pNode;
	int i = 0;
	int max = List_Count(This->m_pTracks);
	CCaret caret;

	// Checks
	caret.pos.w = This->m_wnd;
	caret.height = -1;
	caret.index = 0;

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

	CDDescList* pDoc = CDDescList_Get();
	CDDescList_StartUpdate(pDoc);

	This->m_flags |= EditFlags_Updating;

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

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

			bool bModified = false;

			if (This->m_ModifiedProps & Prop_Title)
				bModified |= throw_CDTrack_SetMetaString(pTrack, EMetaId_StreamTitle, Icon_GetData(This->m_wnd, Icon_Title));

			if (This->m_ModifiedProps & Prop_Artist)
				bModified |= throw_CDTrack_SetMetaString(pTrack, EMetaId_StreamArtist, Icon_GetData(This->m_wnd, Icon_Artist));

			if (This->m_ModifiedProps & Prop_Collective)
				bModified |= throw_CDTrack_SetMetaString(pTrack, EMetaId_StreamCollective, Icon_GetData(This->m_wnd, Icon_Collective));
			if (bModified) CDTrack_RefreshViews(pTrack, This, bModified);
		}
	}
	catch
	{
		App_ReportException();
	}
	catch_end

	This->m_flags |= EditFlags_Updating;

	CDDescList_EndUpdate(pDoc);

	if (off) WLib_Hourglass_Off();

	// Reset settings
	EditCDTrack_BuildProperties(This);
	EditCDTrack_BuildCommonStatus(This);

	return true;
}

static void EditCDTrack_OnCancel(EditCDTrack* This)
{
	// Reset settings
	EditCDTrack_BuildProperties(This);
	EditCDTrack_BuildCommonStatus(This);
}

static EListenerAction EditCDTrack_Listener(void* handle, const Event* e)
{
	EditCDTrack* This = handle;

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

	return EListenerAction_ContinueEvent;
}

static EListenerAction EditCDTrack_EventHandler(void* handle, const Event* e)
{
	EditCDTrack* 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_Set:
				{
					if (EditCDTrack_OnOk(This)
					&&  (m->but & EBut_Select))
					{
						Window_Close(This->m_wnd);
					}
				}
				break;
				case Icon_Cancel:
				{
					EditCDTrack_OnCancel(This);
					if (m->but & EBut_Select)
					{
						Window_Close(This->m_wnd);
					}
				}
				break;
			}

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

			switch(pkey->code)
			{
				case 0x1b: // Esc
				{
					EditCDTrack_OnCancel(This);
					Window_Close(This->m_wnd);
					return EListenerAction_StopEvent;
				}
				break;
				case 0x0d: // Return
				{
					if (pkey->caret.pos.i == Icon_Collective)
					{
						if (EditCDTrack_OnOk(This))
						{
							Window_Close(This->m_wnd);
						}
					}
					return EListenerAction_StopEvent;
				}
				break;
				case 0x181: // F1
				{
					App_StrongHelp("CDs_Properties");
					return EListenerAction_StopEvent;
				}
				break;
				default:
				{
					switch (pkey->caret.pos.i)
					{
						case Icon_Title:
						{
							EditCDTrack_CheckChanges(This, Prop_Title);
						}
						break;
						case Icon_Artist:
						{
							EditCDTrack_CheckChanges(This, Prop_Artist);
						}
						break;
						case Icon_Collective:
						{
							EditCDTrack_CheckChanges(This, Prop_Collective);
						}
						break;
					}
					break;
				}
			}
		}
		break;
	}

	return EListenerAction_ContinueEvent;
}

static EListenerAction EditCDTrack_OnDocEvent(void* pListener, const Event* pEvent)
{
	EditCDTrack* 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)
			{
				EditCDTrack_OnCancel(This);
				EditCDTrack_ClearTracks(This);
				Window_Close(This->m_wnd);
			}
		}
		break;
	}

	return EListenerAction_ContinueEvent;
}

void EditCDTrack_Edit(List* pList, const CDTrack* pRef)
{
	EditCDTrack* This = &TheEditCDTrack;

	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("PropCDTrack", "TCDPrH");
			throw_Window_RegisterEventHandler(This->m_wnd, EditCDTrack_EventHandler, This, false);

			This->m_pWCollectiveList = throw_New_WStringList(DigitalCD.pCollectivesCol, This->m_wnd, Icon_Collective);
			This->m_pWArtistList = throw_New_WStringList(DigitalCD.pArtistsCol, This->m_wnd, Icon_Artist);
			throw_Task_AddListener(EEvent_OptionParentalLock, EditCDTrack_Listener, This, false);
			throw_DocEvents_AddListener(NULL, This, EditCDTrack_OnDocEvent);
		}
		catch
		{
			EditCDTrack_NotEdit();
			App_ReportException();
			return;
		}
		catch_end
	}

	EditCDTrack_ClearTracks(This);

	try
	{
		if (pList && List_Count(pList))
		{
			ListNode* pNode = NULL;
			const CDTrack* pTrack;

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

				List_InsertBefore(This->m_pTracks, NULL, pTrack);
			}
		}
	}
	catch
	{
		App_ReportException();
	}
	catch_end

	EditCDTrack_SetRefTrack(This, pRef);

	if (!List_Count(This->m_pTracks))
	{
		Window_Close(This->m_wnd);
	}
	else
	{
		EditCDTrack_BuildProperties(This);
		EditCDTrack_BuildCommonStatus(This);

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

void EditCDTrack_NotEdit(void)
{
	EditCDTrack* This = &TheEditCDTrack;

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

	Delete_WStringList(This->m_pWCollectiveList);
	Delete_WStringList(This->m_pWArtistList);

	if (This->m_wnd != HWind_None)
	{
		DocEvents_RemoveListener(NULL, This, EditCDTrack_OnDocEvent);
		Task_RemoveListener(EEvent_OptionParentalLock, EditCDTrack_Listener, This);
		Window_DeRegisterEventHandler(This->m_wnd, EditCDTrack_EventHandler, This);
		Window_Delete(This->m_wnd);
	}

	mem_free(This->m_ref.title);
	mem_free(This->m_ref.artist);
	mem_free(This->m_ref.collective);

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