/*
 * Copyright (c) 1993 Michael D. Bayne.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *    following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * 3. All advertising materials mentioning features or use of this software must display the following
 *    acknowledgement:
 *
 *       This product includes software developed by Michael D. Bayne.
 *
 * 4. My name may not be used to endorse or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY MICHAEL D. BAYNE ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL MICHAEL D. BAYNE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <exec/types.h>
#include <exec/memory.h>

#include <dos/dos.h>
#include <workbench/startup.h>
#include <workbench/workbench.h>

#include <libraries/iffparse.h>
#include <libraries/reqtools.h>

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/reqtools_protos.h>
#include <clib/graphics_protos.h>
#include <clib/iffparse_protos.h>
#include <clib/icon_protos.h>
#include <clib/wb_protos.h>

#include "defs.h"
#include "Blanker.h"

#define ID_PREF MAKE_ID('P','R','E','F')
#define ID_PRHD MAKE_ID('P','R','H','D')
#define ID_BLNK	MAKE_ID('B','L','N','K')

UWORD RangeRand( UWORD );
VOID setPrefs( struct bPrefObject *, UBYTE );
VOID UpdateCX( VOID );
VOID loadModule( ULONG );
LONG sendModMsg( ULONG );

extern ULONG validPrefs, tags[];
extern struct bPrefObject bPrefs;
extern struct Port *modulePort;

UBYTE *doPath( UBYTE *file, UBYTE *dir )
{
	static UBYTE path[256];

	CopyMem( dir, path, 108 );
	if( !AddPart( path, file, 256 )) return( 0L );
	return( path );
}

VOID prefError( LONG rc )
{
	const char *errMsgs[] = {	"IFF handle allocation failed. (1)",
					"Open() (for read) failed on pref file. (2)",
					"OpenIFF() (for read) failed on pref file. (3)",
					"No BLNK chunk found in pref file. (4)",
					"Internal error (Context Node retrieval failed). (5)",
					"Open() (for write) failed on pref file. (6)",
					"OpenIFF() (for write) failed on pref file. (7)"
				};

	rtEZRequest( "Error processing preferences file:\n\n%s", "Ok", 0L, BTAGS, errMsgs[rc-1] );
}

LONG loadBlankerPrefs( UBYTE *file, UBYTE *dir, struct bPrefObject *bPO )
{
	struct IFFHandle *bHandle;
	struct ContextNode *top;
	LONG rc = -1, err;

	if(!( bHandle = AllocIFF())) return( 1 );

	if( bHandle->iff_Stream = (ULONG)Open( doPath( file, dir ), MODE_OLDFILE )) {
		InitIFFasDOS( bHandle );

		if( !OpenIFF( bHandle , IFFF_READ )) {
			while( rc == -1 ) {
				err = ParseIFF( bHandle, IFFPARSE_RAWSTEP );
				switch( err ) {
				case IFFERR_EOC:
				if( top = CurrentChunk( bHandle )) {
					if(( top->cn_Type == ID_PREF )&&( top->cn_ID == ID_BLNK )) {
						ReadChunkBytes( bHandle, bPO, sizeof( struct bPrefObject ));
						if( modulePort ) sendModMsg( BM_DOQUIT );
						loadModule( rc = 0 );
						if( BlankerWnd ) setPrefs( &bPrefs, Blanker_CNT );
						UpdateCX();
					}
				} else rc = 5;
				break;
				case 0:
					break;
				default:
					rc = 4;
					break;
				}
			}
			CloseIFF( bHandle );
		} else rc = 3;
		Close( bHandle->iff_Stream );
	} else rc = 2;
	FreeIFF( bHandle );

	return( rc );
}

LONG loadPrefsFromWBArgList( struct WBArg *WBArgs, ULONG numArgs, struct bPrefObject *bPO )
{
	LONG	i, rc = 0L;
extern	UBYTE	prefDir[];

	for( i = 0; i < numArgs; i++, WBArgs++ )
		if( WBArgs->wa_Name && NameFromLock( WBArgs->wa_Lock, prefDir, 108 ))
			if(!( rc = loadBlankerPrefs( WBArgs->wa_Name, prefDir, bPO ))) break;
	return( rc );
}

LONG saveBlankerPrefs( UBYTE *file, UBYTE *dir, struct bPrefObject *bPO, ULONG saveIcon )
{
	struct IFFHandle *bHandle;
	struct DiskObject *pDO;
	UBYTE prefHead[] = {0,0,0,0,0,0}, *oldDefTool;
	LONG rc = 0;

	if(!( bHandle = AllocIFF())) return( 1 );

	if( bHandle->iff_Stream = (ULONG)Open( doPath( file, dir ), MODE_NEWFILE )) {
		InitIFFasDOS( bHandle );

		if( !OpenIFF( bHandle , IFFF_WRITE )) {
			PushChunk( bHandle, ID_PREF, ID_FORM, IFFSIZE_UNKNOWN );

			PushChunk( bHandle, ID_PREF, ID_PRHD, 6 );
			WriteChunkBytes( bHandle, prefHead, 6 );
			PopChunk( bHandle );

			PushChunk( bHandle, ID_PREF, ID_BLNK, sizeof( struct bPrefObject ));
			WriteChunkBytes( bHandle, bPO, sizeof( struct bPrefObject ));
			PopChunk( bHandle );

			PopChunk( bHandle );
			CloseIFF( bHandle );

			if( saveIcon &&( pDO = GetDiskObjectNew( "ENVARC:sys/def_pref" ))) {
				oldDefTool = pDO->do_DefaultTool;
				pDO->do_DefaultTool = "Blanker";
				PutDiskObject( doPath( file, dir ), pDO );
				pDO->do_DefaultTool = oldDefTool;
				FreeDiskObject( pDO );
			}
		} else rc = 7;
		Close( bHandle->iff_Stream );
	} else rc = 6;
	FreeIFF( bHandle );

	return( rc );
}

VOID FreeRPList( struct randPrefList *rPL )
{
	struct randPrefObject *Temp;

	rPL->rpl_Date.ds_Days = 0L;
	rPL->rpl_Date.ds_Minute = 0L;
	rPL->rpl_Date.ds_Tick = 0L;
	rPL->rpl_Number = 0;
	while( rPL->rpl_Head ) {
		Temp = rPL->rpl_Head;
		rPL->rpl_Head = Temp->rpo_Next;
		FreeMem( Temp, sizeof( struct randPrefObject ));
	}
}

VOID buildRandList( struct randPrefList *rPrefs, UBYTE *dir )
{
	struct	FileInfoBlock *Blk;
	struct	randPrefObject *Current;
	BPTR	lock;

	if(( Blk = AllocDosObject( DOS_FIB, 0L ))&&( lock = Lock( dir, ACCESS_READ ))&&( Examine( lock, Blk ))) {
		if( CompareDates( &rPrefs->rpl_Date, &Blk->fib_Date ) > 0 ) {
			FreeRPList( rPrefs );
			CopyMem( &Blk->fib_Date, &rPrefs->rpl_Date, sizeof( struct DateStamp ));
			while( ExNext( lock, Blk )) {
				if(( Blk->fib_DirEntryType < 0 )&&
					( Current = AllocMem( sizeof( struct randPrefObject ), MEMF_CLEAR ))) {
					CopyMem( Blk->fib_FileName, Current->rpo_Name, 108 );
					rPrefs->rpl_Number += 1;
					Current->rpo_Next = rPrefs->rpl_Head;
					rPrefs->rpl_Head = Current;
				}
			}
			if( IoErr() != ERROR_NO_MORE_ENTRIES ) rPrefs->rpl_Number = 0;
		}
	}
	if( Blk ) FreeDosObject( DOS_FIB, Blk );
	if( !rPrefs->rpl_Number ) FreeRPList( rPrefs );
}

VOID loadRandPrefs( struct randPrefList *rPL, struct bPrefObject *bPO, UBYTE *dir )
{
	UWORD i, num;
	struct randPrefObject *Current;

	buildRandList( rPL, dir );

	if( rPL->rpl_Number ) {
		num = RangeRand(( UWORD )rPL->rpl_Number );
		for( i = 0, Current = rPL->rpl_Head; i < num; ++i, Current = Current->rpo_Next );
		loadBlankerPrefs( Current->rpo_Name, dir, bPO );
	}
}
