#!/usr/bin/perl
##################################
#
# user_database.pl stores and searches a database
# of names and addresses.
#
# class demo program
# Jim Mahoney
# September 30, 2004
#
# Here's what we want it to do :
# 
# prompt$ ./user_database.pl
#  What do you want to do?
#   search       type a user's name 
#   input        enter a new name and address
#  ? input
#   name is ? Bob Jones
#   adress ? somewhere
#  OK.
#  What do you want to do?
#   search       type a user's name 
#   input        enter a new name and address
#  ? search
#  who do you want ? Bob
#   who:   Bob Jones
#   where: somewhere
#  What do you want to do?
#   search       type a user's name 
#   input        enter a new name and address
#  ?
#
##################
use strict;
use warnings;
my $DEBUG = 0;    #  1 => print debug info,  0 => don't

# input/output data file
my $filename = "./datafile";

# ask user what to do in a loop until she quits.
while(1){
  prompt();
}

# ==== subroutines ==================================

# Ask user what to do, and do that.
sub prompt {
  print "
What do you want to do?
 search       type a user's name
 input        enter a new name and address
 quit         quit the program
";
  my $choice = get_text_from_user('');


  if ( $choice =~ /^s/ ) {
    search()
  } 
  elsif ( $choice =~ /^i/ ) {
    input()
  } 
  elsif ( $choice =~ /^q/ ) {
    print " Bye...\n";
    exit;
  }
  else {
    print " I didn't understand that.  Try again.\n";
  }
}

# look in the database for a username
sub search {
  print " DEBUG: in search subroutine \n" if $DEBUG;
  my $who = get_text_from_user('who');
  open(DATABASE, "< $filename")
    or die "Oops - couldn't read from '$filename'";
  while( my $line = <DATABASE>){
    if ( $line =~ /^user.*$who/ ){
      print $line;
      my $next_line = <DATABASE>;
      print $next_line;
      return;
    }
  }
  print " Couldn't find '$who'.\n";
}

# enter a new user and address
sub input {
  print " DEBUG: in input subroutine \n" if $DEBUG;
  my $name    = get_text_from_user('name');
  my $address = get_text_from_user('address (one line) ');
  open(DATABASE, ">> $filename")
    or die "Oops - couldn't append to '$filename'";
  print DATABASE "user: ",    $name ,    "\n";
  print DATABASE "address: ", $address,  "\n";
  close DATABASE;
}

# input: a prompt string
# output: what the user typed
sub get_text_from_user {
  my ($prompt_string) = @_;
  print "  $prompt_string ? ";
  my $text = <>;
  chomp($text);
  print " DEBUG: you typed '$text'.\n" if $DEBUG;
  return $text;
}
