#!/usr/bin/ruby
require 'rubygems'
require 'xml/smart'

stellungen = %w{2172 2232 2243 2253 2293 2762 2782 2863 3072 3142 3922 3932 4062 4102 4172 4182 4252 4322 4342 4552 4562 4362 4262}
gruppen = [
  [ 'A782', 'Fachdidaktik'],
  [ 'A783', 'Theory and Applications of Algorithms'],
  [ 'A784', 'Scientific Computing'],
  [ 'A785', 'Software Architecture'],
  [ 'A786', 'Future Communication'],
  [ 'A787', 'Entertainment Computing'],
  [ 'A788', 'Multimedia Information Systems'],
  [ 'A789', 'Knowledge Engineering'],
  [ 'A791', 'Workflow Systems and Technology'],
  [ 'A792', 'Data Analytics and Computing'],
  [ 'A793', 'Bioinformatics and Computational Biology']
]

users = []
userlist = {}
XML::Smart.open('/tmp/faculty.xml') do |doc|
  gruppen.each do |k,v|
    # puts v
    doc.find("/personenverzeichnis/person[@aktiv='ja' and */@inum='#{k}  ']").each do |p|
      if p.attributes['email'] != '' && p.attributes['username'] != ''
        stells = []
        p.find("*[@inum='#{k}  ']/@stellungen").each{ |s| stells += s.to_s.split(',') }
        success = false
        stells.each do |stell|
          success = true if  stellungen.include?(stell)
        end
        if success
          inums = p.find('*/@inum').map{ |inum| gruppen.assoc(inum.to_s.strip) ? inum.to_s[1..3] : nil }.compact.uniq
          users << p.attributes['username']
          userlist[p.attributes['username']] = "<person group=\"#{inums.join(',')}\" team=\"\" admin=\"false\" name=\"#{p.attributes['vorname'] + " " + p.attributes['zuname']}\" email=\"#{p.attributes['email']}\" id=\"#{p.attributes['username']}\"/>" << "<!-- stellungen=\"#{stells.join(',')}\" -->"  
        end
      end  
    end
  end 

  puts "</persons>"
  users.uniq.each do |u|
    puts userlist[u]
  end
  puts "<persons>"
end  
