package xm::css::find;
use xm::css::sheet;
use xm::o;

# return a number on how many chars at the start
# of the two strings are equal
# use: while looking for a css-file that matches
#      an xm-source best by its filename
sub headmatch
{
    my ($a,$b) = @_;
    my $len = length $a;
    $len = length $b if $len > length $b;

    my $i = 1;
    while ($i <= $len and substr($a,0,$i) eq substr($b,0,$i))
    {
	$i += 1;
    }
    
    return $i - 1;
}

sub DESC {" 
 given a filename, tries to find a css-file
 that matches most closely. It basically walks
 the directory of the referenced filename and
 looks for a css-file with the longest match.
 if no filename is in the current directory,
 it will cd up and looks for css-file most
 closely matching the dir-name. If not css-file
 is there either it returns undef
"}

sub file
{
    my $F = shift;
    my $D = $F;

    return $F if $F =~ /\.css$/;

    if ($D =~ /\//)
    {
	$D =~ s{ /[^/]*$ } { }sx;
    }else{
	$D = ".";
    }

    my $matchfile = "";
    my $matchlen = -1;

    if (opendir D,"$D")
    {
	my $E;
	while ($E = readdir D)
	{
	    if ($E =~ /\.css$/)
	    {   
		my $len = headmatch($F,$E);
		if ($matchlen < $len)
		{
		    $matchlen = $len;
		    $matchfile = $E;
		}
	    }
	}
	closedir D;
    }

    return $matchfile if $matchlen >= 0;
    $matchlen = 0;

    $F  = `pwd`;
    $F .= ".";
    $D = $F;
    $D =~ s{ /[^/]*$ } { }sx;

    if (opendir D,"$D")
    {
	my $E;
	while ($E = readdir D)
	{
	    if ($E =~ /\.css$/)
	    {
		my $len = headmatch($F,$E);
		if ($matchlen < $len)
		{
		    $matchlen = $len;
		    $matchfile = $E;
		}
	    }
	}
	closedir D;
    }

    return $matchfile;
}

sub DO 
{
    my $A = $_[0];
    my $a;
    my $x = "";

    for $a (@$A)
    {
	my $css = xm::css::find::file($a);
	if (defined $css)
	{
	    $x .= $a. " <> ".$css;
	}else{
	    $x .= $a." (no cssfile found)";
	}
	$x .= "\n";
    }
    return $x;
}

sub ARGS { return    xm::o::args_files(@_,DESC); }
sub main { return DO(xm::o::args_files(@_,DESC)); }

# try to create a css sheethash by finding a css file
# as derived from the filename argument. return the css-sheethash.
sub fileandload
{
    my $F;
    my %files;
    my $bestcss = "";
    my $bestlen = -1;
    my $csstext = "";

    for $F (@_)
    { 
	if (length $F)
	{
	    my $f = xm::css::find::file($F);
	    next if not defined $f;
	    my $l = headmatch ($F, $f);
	    $bestcss = $f if ($l > $bestlen);
	}
    } 
    return undef if not length $bestcss;

    $F = $bestcss;
    return undef if not open F,"<$F";
    $csstext = join ("",<F>);
    close F;

    return undef if not length $csstext;
    return xm::css::sheet::mksheet($csstext);
}

1;