#include	<exec/types.h>

#include	<utility/tagitem.h>
#include	<exec/memory.h>

#include	<proto/exec.h>
#include	<proto/dos.h>
#include	<proto/gadtools.h>
#include	<proto/intuition.h>
#include	<proto/xsl.h>
#include	<clib/alib_protos.h>

#include <libraries/p4specials.h>
#include	<proto/picasso96.h>

#include	<stdio.h>

#include "cs.h"
#include "cs_sup.h"
#include "tv.h"

struct List TempList;	/* for a work list during the Requester */
struct Node *TempNode;
int setupcode;

int TempNumChannels, TempChannelIndex;

void cs_init(void)
{
}

int Setup(void)
{
	struct Node *n;
	struct TVchannelHandle *handle, *temphandle;
	
	TempNumChannels = NumChannels;
	TempChannelIndex = ChannelIndex;
	setupcode = SETUP_CANCEL;

	NewList(&TempList);
	for(handle = (struct TVchannelHandle *)ChannelList.lh_Head; handle->Node.ln_Succ; handle = (struct TVchannelHandle *)handle->Node.ln_Succ){
		if(temphandle = AllocVec(sizeof(*temphandle),MEMF_ANY)){
			temphandle->Channel = handle->Channel;
			if(temphandle->Node.ln_Name = CloneStr(handle->Node.ln_Name)){
				AddTail(&TempList, (struct Node *)temphandle);
			}else{
				FreeVec(temphandle);
			}
		}
	}
	TempNode = FindNumber(&TempList, TempChannelIndex);
	if(!SetupScreen()){
		if(!OpenCSWindow()){
			SetWindowPointer(wd, WA_BusyPointer, TRUE, TAG_END);
			GT_SetGadgetAttrs(CSGadgets[GD_Channels], CSWnd, NULL, GTLV_Selected, TempChannelIndex, TAG_END);
			GT_SetGadgetAttrs(CSGadgets[GD_Name], CSWnd, NULL, GTST_String, TempNode->ln_Name, TAG_END);
			do{
				Wait(1L << (CSWnd->UserPort->mp_SigBit));
			}while(HandleCSIDCMP());
			CloseCSWindow();
			SetWindowPointer(wd, WA_BusyPointer, FALSE, TAG_END);
		}
		CloseDownScreen();
	}
	switch(setupcode){
	case	SETUP_USE:
	case	SETUP_SAVE:
		while(n = RemHead(&ChannelList)){
			FreeVec(n->ln_Name);
			FreeVec(n);
		}
		ChannelList.lh_Head = TempList.lh_Head;
		ChannelList.lh_TailPred = TempList.lh_TailPred;
		NumChannels = TempNumChannels;
		ChannelIndex = TempChannelIndex;

		if(setupcode == SETUP_SAVE)
			WriteSettings();
		break;
	case	SETUP_CANCEL:
		while(n = RemHead(&TempList)){
			FreeVec(n->ln_Name);
			FreeVec(n);
		}
		if(NumChannels){
			SetChannel(ChannelIndex);
			sprintf(WindowTitle,"Paloma TV Demo Channel: \"%s\"",FindNumber(&ChannelList, ChannelIndex)->ln_Name);
			SetWindowTitles(wd,WindowTitle,WindowTitle);
		}
		break;
	}
	return(1);
}

void BeginListAction(void)
{
	GT_SetGadgetAttrs(CSGadgets[GD_Channels], CSWnd, NULL, GTLV_Labels, (ULONG)~0, TAG_END);
}

void EndListAction(void)
{
	int num = 0;
	if(TempNode){
		num = NodeNumber(&TempList, TempNode);
	}
	GT_SetGadgetAttrs(CSGadgets[GD_Channels], CSWnd, NULL, 
							GTLV_Labels, (ULONG)&TempList,
							TempNode ? TAG_IGNORE : TAG_SKIP, 2,
							GTLV_MakeVisible, num,
							GTLV_Selected, num,
							TAG_END);
}
