# -*- coding: utf-8 -*-
require 'dbi'
require 'yaml'

class DbController
  @@dbh = nil
  def self.get_connection
    begin
      if @@dbh.nil?
        # connect to the postgreSQL server
#        url = "DBI:Pg:e_prtr:pg84.enda.eu"
#        user = "e_prtr"
puts "current working directory: #{Dir.getwd}"
        config = YAML.load_file("config/db.yml")
        puts "Connecting to Database (url #{config['url']} ; user #{config['user']} )"
        #        puts "Please enter password"
        #        oldstty=`stty -g`
        #        `stty -echo`
        #        passwd = gets.strip
#        passwd = 'e_prtr'
        #        system "stty #{oldstty}"
        @@dbh = DBI.connect(config['url'], config['user'], config['password'])
        # get server version string and display it
        row = @@dbh.select_one("SELECT VERSION()")
        puts "Server version: " + row[0]
      end
    rescue DBI::DatabaseError => e
      puts "An error occurred"
      puts "Error code: #{e.err}"
      puts "Error message: #{e.errstr}"
      exit
#    rescue SystemExit, Interrupt
#      system "stty #{oldstty}"
#      Process.exit(1)
#    ensure
      ## disconnect from server
      #dbh.disconnect if @dbh
    end
    return @@dbh
  end



  def self.close_connection
    @@dbh.disconnect if @@dbh
  end
end