#
#  Machine.pm
#  --machine object for mchange
#

package Mchange::Machine;

use strict;
use lib '/afs/.cs.wisc.edu/s/mchange-2.2/common/perl5';

#every machine has parts and attributes associated with them
use Mchange::Part;
use Mchange::Attribute;

use DBI;
use CSL::Pg;
use CSL::DBs;

use Data::Dumper;

use vars qw( $AUTOLOAD );

#
#  $parts => array ref to list of Mchange::Part
#  $attrib => ref to Mchange::Attrib
#

sub new {

  my ( $class, $parts, $attrib ) = @_;

  #this is a more efficient internal structure
  my $default = \%$attrib;
  
  my $ref = { parts => $parts,
              attrib => $attrib,
              default => $default };

  return bless( $ref, $class );
    
}

sub DESTROY {


}

sub AUTOLOAD {

  my ( $self, $arg ) = @_;

  $AUTOLOAD =~ m/::(\w*)$/ || die "Machine.pm--No such method: $AUTOLOAD\n"; 

  if ( $arg ) {
    return $self->{attrib}->set( $1, $arg );    
  }
  else {
    return $self->{attrib}->get( $1 );
  }

}

#
#  get_parts
#  --return a hash of parts
#

sub get_parts {

  my ( $self ) = @_;

  return $self->{parts};
  
}

#
#  get_attrib
#  --return the entire list of attribs
#

sub get_attrib {

  my ( $self ) = @_;

  return $self->{attrib};

}


#
#  add_part
#  --add a part to the machine
#

sub add_part {

  my ( $self, $part ) = @_;
  $self->{parts}{$part->invnum} = $part;
}

#
#  copy
#  --return a deep copy of the machine
#

sub copy {

  my ( $self ) = @_;

  my %newparts;

  map { $newparts{$_} = $self->{parts}{$_}->copy } keys %{$self->{parts}};

  return new Mchange::Machine( \%newparts, $self->{attrib}->copy );
  
}

#
# get_users
# --returns a list of all authorized users for a machine
#

sub get_users {
    my ( $self, $name ) = @_;

#my $name = $self->get_cpuname;

    my $query_text = <<QUERY
SELECT 
  people."login"
FROM 
  csdb.accounts, 
  csdb.people
WHERE
  people.uid = accounts.uid AND
  accounts.machine LIKE '$name'
QUERY
;
   

    my $db = DBI->connect($CSL::DBs::csdb);
    my $query = $db->prepare($query_text);
    if(!$query->execute()) {
        die("ERROR: Select authorized users query failed\n");
    }

    my @users;
    my $labacct = 0;

    while(my $row = $query->fetchrow_hashref) {
        my $user = $row->{login};
        # Check to see if user is labacct because we always 
        # want to add labacct to the machine users list.
        if($user eq "labacct")
        {
            $labacct = 1;
        }
        push @users, $user;
    }

    $db->disconnect;

    if($labacct == 0)
    {
        push @users, "labacct";
    }

    return @users;
}


    

sub print_info {

  my ( $self ) = @_;

  print "====================\n";
  print "Info for " . $self->get_cpuname . "\n";
  #print Dumper( $self );  
  
}


1;
