# Copyright 2002-2007 Interchange Development Group and others
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  See the LICENSE file for details.
# 
# $Id: db_columns.coretag,v 1.5 2007-03-30 23:40:54 pajamian Exp $

UserTag db_columns  Order       name columns joiner passed_order
UserTag db_columns  AttrAlias   table name
UserTag db_columns  AttrAlias   fields columns
UserTag db_columns  Version     $Revision: 1.5 $
UserTag db_columns  Routine     <<EOR
sub {
	my ($table,$columns, $joiner, $passed_order) = @_;
	$table = $Values->{mv_data_table}
		unless $table;
	my $db = Vend::Data::database_exists_ref($table)
		or return undef;
	my $acl = UI::Primitive::get_ui_table_acl($table);
	$db = $db->ref() unless $Vend::Interpolate::Db{$table};
	my $key = $db->config('KEY');

	$joiner = "\n" unless defined $joiner;

	my @cols;
	if(! $columns || $columns =~ /^[\s,\0]*$/) {
		@cols = $db->columns();
	}
	else {
		@cols = grep /\S/, split /[\s,\0]+/, $columns;
		my (@allcols) =  $db->columns();

		my %col;
		if($passed_order) {
			@col{@allcols} = @allcols;
			@allcols = @cols;
			my $found;
			for(@cols) {
				next unless $_ eq $key;
				$found = 1;
				last;
			}
			unshift (@allcols, $key) if ! $found;
		}
		else {
			@col{@cols} = @cols;
		}

		$col{$key} = $key if ! defined $col{$key};

		@cols = grep defined $col{$_}, @cols;
	}

	if($acl) {
		@cols = UI::Primitive::ui_acl_grep( $acl, 'fields', @cols);
	}

	return @cols if wantarray;
	return join $joiner, @cols;
}
EOR
