# -*- coding: utf-8 -*-
# 2016-08-12 mlt: Schwerwiegendes Problem in query-Funktion behoben.
#   Fehlende Fehlerbehandlung im rescue-Ast und raisen einer neuen, kommentarlosen Exception
#   führte zur Unterdrückung des eigentlichen Fehlers und somit zu fehlleitenden Informationen.
#
require 'dbi'
require 'yaml'
require 'sqlite3'

class DbController

  #expects config file path from working directory
  def initialize(config_file)
    begin
      puts "loading file: #{config_file}"
      config = YAML.load_file(config_file)
      puts "data should be loaded into config. We have got"
      puts "config['url']: #{config['url']}"
      puts "config['userl']: #{config['user']}"
      # puts "config['password']: #{config['password']}"
      puts "config['password']: <sagichnicht>"
      # h1 = { 'url' => 'DBI:Pg:e_prtr:localhost', 'user' => 'uba', 'password' => 'bla' }
      # File.open('mytestyaml.yml', 'w') {|f| f.write h1.to_yaml }
      
      @handle = DBI.connect(config['url'], config['user'], config['password'])
      puts "current working directory: #{Dir.getwd}"
      puts "Connecting to Database (url #{config['url']} ; user #{config['user']} )"
    rescue DBI::DatabaseError => e
      puts "An error occurred"
      puts "Error code: #{e.err}"
      puts "Error message: #{e.errstr}"
      exit
    rescue Exception => wumm
      puts "Unexpected <#{wumm}>."
      print wumm.backtrace.join("\n")
      exit 1;
    end
  end

  def query(stmt)
    begin
      @handle.execute(stmt)
    rescue SystemExit, Interrupt, Exception => rumms
      warn "Fehler bei Datenbankabfrage(Exception) #{stmt}"
      warn "*****\n" + rumms.message + "*****"
      warn rumms.backtrace.join("\n")
      raise rumms
    end
  end

  def query_one(stmt)
    rs = query(stmt)
    return rs.to_a[0][0] rescue nil
  ensure
    rs.finish
  end

#returns no resultset
  def execute(stmt)
    begin
      @handle.do(stmt)
    rescue
      warn "Fehler bei Datenbankabfrage: #{stmt}"
      raise
    end
  end

  def prepare(stmt)
    begin
      @handle.do(stmt)
    rescue
      warn "Fehler bei Datenbankabfrage: #{stmt}"
      raise
    end
  end


  def close_connection
    @handle.disconnect if @handle
  end
end
