# Create/populate the emr_database with random patients and 
# associated charts

NUM_PATIENTS = 10
NUM_CHARTS = 100

# Reinitialize the database (just to be safe, we'll drop the
# entire datatabase and recreate the schema.)
system(<<-"EOF")
mysql -u emrdev -pd3v1 -e \
"DROP DATABASE if exists emr_development;

CREATE DATABASE emr_development;

USE emr_development;

CREATE TABLE patients (
  id			int unsigned		NOT NULL auto_increment,
  given_names		varchar(64)		NOT NULL,
  last_name		varchar(64)		NOT NULL,
  mcp_number		varchar(12)		NOT NULL,
  address1		varchar(64)		NOT NULL,
  address2		varchar(64)		NOT NULL,
  dob			date			NOT NULL,

  PRIMARY KEY(id)
);

CREATE TABLE charts (
  id			int unsigned		NOT NULL auto_increment,
  patient_id		int unsigned		NOT NULL,
  comment 		varchar(255)		NOT NULL,
  weight		int(4)			NOT NULL,
  height		int(4)			NOT NULL,
  date		        date			NOT NULL,

  PRIMARY KEY(id)
);"
EOF

# Extend the Array class to make it easier to extract random elements
# (names in our case) from an Array.
#
class Array
  def random
    self[rand(length)]
  end
end

male   = %w(Anthony Bob Charles David Edgar Frank)
female = %w(Alice Barbara Cynthia Donna Elizabeth Felicity)
last   = %w(Andrews Burns Collins Doe Evans Flynn)

tree = %w(Poplar Larch Maple Elm Pine)
road_type = %w(Cresent Lane Street Place)

cities = { 
	"NL" => %w(
		St.\ John's 
		Carbonear 
		Bay\ Roberts 
		Cupids 
		Bauline 
		Torbay 
		Labrador\ City
		Goose\ Bay),
	"NS" => %w(
		Halifax
		Truro
		Pictou
		Bridgewater
		Kentville
		Sydney),
	"QC" => %w(
		Chicoutimi 
		Gatineau
		Rimouski)
}


comments = [
  "Runny nose",
  "High blood pressure",
  "Suffering from cooties",
  "Dislocated shoulder",
  "Shortness of breath",
  "Missing an elbow",
  "Dilated pupils",
  "Ants in the pants",
]

NUM_PATIENTS.times { 
  prov = rand < 0.80 ? "NL" : rand > 0.5 ? "NS" : "QC"
  dob = (DateTime.now - rand(30000)).strftime("%Y-%m-%d")
  Patient.create(:mcp_number  => (1..12).map { rand(10) }.join,
                 :last_name   => last.random,
                 :given_names => rand > 0.5 ? male.random : female.random,
                 :address1    => "%d %s %s" % 
		 		[rand(300)+1, tree.random, road_type.random],
                 :address2    => "%s %s" % [cities[prov].random, prov],
                 :dob         => dob)
}

NUM_CHARTS.times {
  patient = Patient.find(rand(NUM_PATIENTS) + 1)
  lifetime_days = (DateTime.now - patient.dob).to_i
  date = (DateTime.now - rand(lifetime_days)).strftime("%Y-%m-%d")
  patient.charts.create(:date	    => date,
                        :weight	    => rand(100)+20,
                        :height	    => rand(200)+30,
	                :comment    => comments.random)
}

require 'pp'
for patient in Patient.find(:all) do
  pp patient
  for chart in patient.charts do
    pp chart
  end
  puts "-" * 70
end
