require 'nokogiri'
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter:  'mysql2', # or 'postgresql' or 'sqlite3' or 'oracle_enhanced'
  host:     'localhost',
  database: 'mathmodels',
  username: 'root',
  password: ''
)

doc = Nokogiri::XML(File.open("damm_models.xml"))

# iterate over all <model> nodes
xmodels = doc.xpath('//model')

puts "#{xmodels.length} Modell-Datensätze in XML-Datei gefunden."

models = []

agg = Hash.new(0)

xmodels.each do |xmodel|
  model = {}
  xmodel.children.each do |child|
    if child.name == "text"
      next
    elsif child.name == "id"
      name = "or_id"
    else
      name = child.name
    end
    model[name] = child.content
    agg[name] = child.content.length if child.content.length > agg[name]
  end
  models.push model
end

# drop table if exists
if ActiveRecord::Base.connection.table_exists? :mathmodels
  ActiveRecord::Base.connection.drop_table :mathmodels
end
# create table
ActiveRecord::Base.connection.create_table(:mathmodels) do |t|
  models.first.keys.each do |key|
    t.column key, :string, limit: agg[key]
  end
end

class Mathmodel < ActiveRecord::Base
end

models.each do |model|
  Mathmodel.create(model)
end

puts "#{models.length} Modelle in Datenbank hinzugefügt."

=begin
Felder eines Modells in den XML-Daten
* id
* nameD
* nameE
* nameF
* kurztextD
* kurztextE
* kurztextF
* textD
* textE (leer)
* textF (leer)
* size
* weight
* katalognr
* seit
* ort
* objektnr
* institution
* collection
* owner (leer)
* material
* design
* subject
* category
* topic
* group
* manufacturer
* catalogue
* image
=end
