package MpmasStataGroups;

use strict;
use warnings;
use Exporter;
use Storable qw(dclone);
use Data::Dumper;
use MpmasInputfile;
use MpmasInputBlock;
our @ISA = qw(MpmasInputfile);

sub filename {
	"StataGroups";
}
sub write {
	my $self = shift;
	my @SortedActivityGroupings =sort{$a cmp $b} keys %{$self->config_entry("Groupings")->{activity}}; 
	
	#Group Labels
	my $statagroupout;
	for my $j (@SortedActivityGroupings) {				
	
		open($statagroupout, ">",  $self->outdir.$self->mname."_create_".$j."_uvariables.do") or die "Can't open ".$self->outdir.$self->mname."create_".$j."_variables.do $!";
		my $category_hash ={};
		for my $i ($self->sorted_activities){
				my $k = $self->activity($i);
				if (defined $k->get_group($j) ) {
					my $group = $k->get_group($j);
					my $var = "u".( $k->lp_column + 15);
					push @{$category_hash->{$group}}, $var;
					
				}
		}
		for my $k (sort {$a cmp $b} keys %$category_hash) {
			my $stata_var_name = $j."_".$k;
			print $statagroupout "egen $stata_var_name = rowtotal(".join(" ", @{$category_hash->{$k}}).")\n";
		}
		close $statagroupout;
	}
	my @SortedConstraintGroupings =sort{$a cmp $b} keys %{$self->config_entry("Groupings")->{constraint}}; 
	for my $j (@SortedConstraintGroupings) {				
	
		open($statagroupout, ">",  $self->outdir.$self->mname."_create_".$j."_kvariables.do") or die "Can't open ".$self->outdir.$self->mname."create_".$j."_variables.do $!";
		my $category_hash ={};
		for my $i ($self->sorted_constraints){
				my $k = $self->constraint($i);
				if (defined $k->get_group($j) ) {
					my $group = $k->get_group($j);
					my $var = "r".( $k->lp_row + 15);
					push @{$category_hash->{$group}}, $var;
					
				}
		}
		for my $k (sort {$a cmp $b}  keys %$category_hash) {
			my $stata_var_name = $j."_".$k;
			print $statagroupout "egen $stata_var_name = rowtotal(".join(" ", @{$category_hash->{$k}}).")\n";
		}
		close $statagroupout;
	}

}
1;
