package ACheck::FileType;


use strict;
use Exporter;
use locale;
use File::Spec::Functions qw(rel2abs splitpath splitdir);
use ACheck::Common;

use vars  qw(@ISA @EXPORT);

@ISA	= qw(Exporter);
@EXPORT	= qw(
	file_type
	);

my %FILE_TYPES = (						# filetypes
	'\.wml(\.\w+)?$'	=> "wml",
	'\.po(\.\w+)?$'		=> "po",
	'\.te?xt(\.\w+)?$'	=> "text"
	);


# file_type
#
# find file type
#
# input:
#   filename
#   array reference of file lines
# return:
#   file type
sub file_type ($$) {
	my $filename	= shift || "-";				# filename
	my $lines	= shift;				# array of lines

	debug 1;
	debug 2, "filename:     ".($filename || "STDIN")."\n";

	my $type;					# file type
	my $file   =  "";				# file name
	my $dir    =  "";				# directory
	my @dirs   = ("");				# path

	unless ($filename eq "-") {
		$filename = rel2abs($filename) unless $filename eq "-";
		(undef, $dir, $file) = splitpath($filename);
		@dirs = splitdir($dir);
	}

	#
	# file name tests
	#
	if ($dirs[-1] eq "debian" &&
	    $file     eq "control"  ) {
		$type = "debian-control";
	}

	if ($type) {
		debug 3, "filetype:     $type\n";
		return $type;
	}


	#
	# file extension tests
	#
	foreach (keys %FILE_TYPES) {
		next unless $file =~ /$_/;
		$type = $FILE_TYPES{$_};
		last;
	}

	if ($type) {
		debug 3, "filetype:     $type\n";
		return $type;
	}


	#
	# content tests
	#
	if	($$lines[0] =~ /^--- \w+/    &&		# unified diff tests
		 $$lines[1] =~ /^\+\+\+ \w+/ &&
		 $$lines[2] =~ /^@@ /       ) {
		$type   = "udiff-wml" if $$lines[0] =~ /^\-\-\- \w+\.wml\b/;
		$type   = "udiff-wml" if $$lines[1] =~ /^\+\+\+ \w+\.wml\b/;
		$type ||= "udiff";
	} elsif ($$lines[0] =~ /^#use wml\b/) {
		$type = "wml";
	} else {					# otherwise try to guess from file lines
		my $i;
		for ($i = 0; $i < @{ $lines }; $i++) {
			last unless $$lines[$i] =~ /^#/;
		}
		if	($i == @{ $lines }) {
		} elsif	($$lines[$i  ] =~ /^msgid ""$/ &&
			 $$lines[$i+1] =~ /^msgstr "/    ) {
			$type = "po";
		} elsif ($$lines[$i  ] =~ /^Description: /) {
			$type = "ddts";
		}
	}

	$type ||= "text";				# default to text

	debug 3, "filetype:     $type\n";

	return $type;
}

1;
