#include "CDCmds.h"

#include <time.h>

#include "WimpLib:Message.h"
#include "WimpLib:Task.h"

#include "CDDesc.h"
#include "Cmds.h"
#include "CmdList.h"
#include "DigitalCD.h"
#include "EditCDDesc.h"
#include "EditCDTrack.h"

int CDView_CheckCommand(const View* pView, int cmd, const List* pList, const List* pDescList)
{
	CDDescList* pDoc = (CDDescList*) View_GetDocument(pView);
	int state = 0;

	// Disable any command if a background Job is active
	if (CDDescList_IsBusy(pDoc))
		return state;

	switch(cmd)
	{
		case Cmd_CDList_Save:
		{
			switch (CDDescList_GetType(pDoc))
			{
				case CDDescList_TypeMain:
					state |= ECmdState_Allow;
			}
		}
		break;
		case Cmd_CDList_Reload:
		{
			switch (CDDescList_GetType(pDoc))
			{
				case CDDescList_TypeMain:
					state |= ECmdState_Allow;
			}
		}
		break;
		case Cmd_CDList_EditDelete:
		{
			// Check that there is at least one CDDesc selected item and no selected tracks
			if (!List_Count(pList) && List_Count(pDescList))
			{
				switch (CDDescList_GetType(pDoc))
				{
					case CDDescList_TypeMain:
						state |= ECmdState_Allow;
				}
			}
		}
		break;
		case Cmd_CDList_Properties:
		case Cmd_CDList_CDProperties:
		{
			// Check that there is at least one selected item
			if (List_Count(pList) || List_Count(pDescList))
			{
				state |= ECmdState_Allow;
			}
		}
		break;
		default:
			return App_CheckCommand(NULL, cmd);
	}

	return state;
}

bool CDView_ExecCommand(View* pView, int cmd, List* pList, List* pDescList, const CDTrack* pRefTrack, const CDDesc* pRefDesc)
{
	CDDescList* pDoc = (CDDescList*) View_GetDocument(pView);

	switch(cmd)
	{
		case Cmd_CDList_Save:
		{
			CDDescList_SaveChanges(pDoc);
		}
		break;
		case Cmd_CDList_Reload:
		{
			CDDescList_RevertChanges(pDoc);
		}
		break;
		case Cmd_CDList_EditDelete:
		{
			ListNode* pNode = NULL;

			while ((pNode = List_GetSuccessor(pDescList, pNode)) != NULL)
			{
  				CDDesc* pDesc = List_GetNodeData(pDescList, pNode);

				CDDesc_SetDeletedFlag(pDesc, true);
				CDDesc_SetModifiedFlag(pDesc, true);
			}
		}
		break;
		case Cmd_CDList_Properties:
		{
			if (List_Count(pDescList) > 0)
				EditCDDesc_Edit(pDescList, pRefDesc);
			else
				EditCDTrack_Edit(pList, pRefTrack);
		}
		break;
		case Cmd_CDList_CDProperties:
		{
			ListNode* pNode = NULL;

			if (List_Count(pDescList) == 0)
			{
				pDescList = New_List();
				while ((pNode = List_GetSuccessor(pList, pNode)) != NULL)
				{
					const CDTrack* pTrack = List_GetNodeData(pList, pNode);
					CDDesc* pDesc = CDTrack_GetCDDesc(pTrack);
					if (NULL == List_FindNode(pDescList, NULL, pDesc))
						List_InsertAfter(pDescList, NULL, pDesc);
				}
				pRefDesc = CDTrack_GetCDDesc(pRefTrack);
			}

			EditCDDesc_Edit(pDescList, pRefDesc);
		}
		break;
		default:
			return App_ExecCommand(NULL, cmd);
	}

	return true;
}
