#!/perl -w
# NAME: genjsarray.pl
# AIM: Given an input folder, generate a javascript array of file
# 26/06/2008 geoff mclane - http://geoffair.net/mperl/
use strict;
use warnings;
use File::Basename;
use File::stat;
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
	my @tmpsp = split(/\\/,$pgmname);
	$pgmname = $tmpsp[-1];
}

my $outfile = "temp.$pgmname.txt";

# features
my $recursive = 0;	# set to 1 to be recursinve into sub-folders

open_log($outfile);
prt( "$0 ... Hello, World ...\n" );



my $in_folder = '..\php\pics';

### program constants
my @imglist = ();
my @imgfiles = ( ".jpg" );
my @fpfolders = qw( _vti_cnf _vti_cnf _private _derived );
my $imgcnt = 0;
# debug stuff
my $dbg1 = 0;

collect_image_files( $in_folder );
$imgcnt = scalar @imglist;
prt( "Got $imgcnt files from $in_folder ...\n" );
prt( "var fileList = new Array(\n" );
for( my $i = 0; $i < $imgcnt; $i++ ) {
	my $itm = $imglist[$i];
	my ($nm, $dir, $ext) = fileparse( $itm, qr/\.[^.]*/ );
	prt( "$itm, $nm" );
	if(($i + 1) < $imgcnt) {
		prt( ',' );
	}
	prt( "\n" );
}
# close the array generation
prt( "); // end of list\n" );

close_log($outfile,1);
exit(0);

#############################
sub my_in_file {
	my ($fil) = shift;
	my ($nm, $dir, $ext) = fileparse( $fil, qr/\.[^.]*/ );
	prt( "Checking $nm, $ext in $dir ...\n" ) if ($dbg1);
	if (lc($ext) eq '.jpg') {
		return 1;
	}
	foreach my $e (@imgfiles) {
		if (lc($e) eq lc($ext)) {
			return 1;
		}
	}
	prt( "Extent [$ext] is NOT '.jpg' ...\n" ) if ($dbg1);
	return 0;
}

sub is_fp_folder {
	my ($fil) = shift;
	foreach my $fp (@fpfolders) {
		if (lc($fp) eq lc($fil)) {
			return 1;
		}
	}
	return 0;
}

sub collect_image_files {
	my $inf = shift;
	prt( "Processing $inf folder ...\n" );
	if ( opendir( DIR, $inf ) ) {
		my @files = readdir(DIR);
		closedir DIR;
		my $cnt = scalar @files;
		prt( "Process $cnt directory objects ...\n" );
		foreach my $fl (@files) {
			if (($fl eq '.') || ($fl eq '..') || is_fp_folder($fl) ) {
				prt( "Skipping [$fl] ...\n" ) if ($dbg1);
				next;
			}
			my $ff = $inf . "\\" . $fl;
			if (-d $ff) {
				prt( "Item [$ff] is directory ...\n" ) if ($dbg1);
				if ($recursive) {
					collect_image_files($ff) if ($recursive);
				}
			} else {
				if (my_in_file($fl)) {
					prt( "Adding [$ff] ...\n" ) if ($dbg1);
					push(@imglist, $ff);
				} else {
					prt( "Extent [$fl] is NOT '.jpg' ...\n" ) if ($dbg1);
				}
			}
		}
	} else {
		prt( "WARNING: Can NOT open $inf ... $! ...\n" );
	}
}

# eof
