class MainController < Ramaze::Controller
  layout '/page'
  engine :Haml
  helper :auth

  before(:professors, :grades) { require_auth(:professor) }
  before(:students, :exams, :subscribe) { require_auth(:student) }

  def index
    redirect Rs(:students)
    nil
  end

  def professors
    @title = "welcome to the pruefungssekretariat"
    @professor_active = "active"
    @student_active = "link"

    begin

      if title = request['title'] and date = request['date']
        raise "no title given!" if title.empty?
        raise "no date given!" if date.empty?
        date = DateTime.parse(date)
        Exams.create(:prof_id => @current_id[1], :description => title, :date => date.to_s)
      end

      @exams = Exams.filter(:prof_id => @current_id[1]).order(:date).map { |x| x = [ A(x[:description], :title => "enter grades for this exam", :href => Rs(:grades, x[:id])), x[:date].strftime("%Y-%m-%d %H:%M") ] }
      
    rescue 
      @error = $!
    end

    nil
  end

  def students
    @title = "welcome to the pruefungssekretariat"
    @professor_active = "link"
    @student_active = "active"
    
    @professors = Professors.to_hash(:id, :name).to_a.map { |x| x = A(x[1], :title => "show this prof's exams", :href => Rs(:exams, x[0]))}
    
    nil
  end

  def exams(prof_id)
    @title = "exams of professor " << Professors[prof_id].name
    @professor_active = "link"
    @student_active = "active"
   
    @exams = Exams.filter('date > ?', Date.today.to_s).filter(:prof_id => prof_id).order(:date).map { |x| 
         x = if Students[@current_id[1]].is_subscribed?(x[:id])
               [ ((grade = Grades.filter(:student_id => @current_id[1], :exam_id => x[:id]).first.grade) > 0 ? "you've got a #{grade.to_s} in #{x[:description]}" : "no grade given yet"), x[:date].strftime("%Y-%m-%d %H:%M") ]  
             elsif
               Ramaze::Log.debug "" # wtf? if I don't do this, this element becomes nil?!
               [ A("subscribe to " << x[:description], :title => "subscribe for this exam", :href => Rs(:subscribe, x[:id])), x[:date].strftime("%Y-%m-%d %H:%M") ]  
             end
    }
    
    nil
  end
  
  def grades(exam_id)
    @title = "grades for exam " << Exams[exam_id].description
    @professor_active = "active"
    @student_active = "link"

    if request.env["REQUEST_METHOD"] == "POST"
      for param in request.params
        student_id, grade = *param
        Grades.filter(:student_id => student_id, :exam_id => exam_id).update(:grade => grade) if (1..6).include? grade.to_i
      end
      redirect Rs(:professors)
    end
    
    @grades = Grades.filter(:exam_id => exam_id)
 
    nil
  end
  
  def subscribe(exam_id)
    @title = "you've subscribed successfully"
    @professor_active = "link"
    @student_active = "active"

    begin

      raise "you are already subscribed for this exam" if Students[@current_id[1]].is_subscribed?(exam_id)

      Grades.create(:student_id => @current_id[1], :exam_id => exam_id, :grade => 0)
    
      "don't forget the exam, it's on " << Exams[exam_id].date.strftime("%Y-%m-%d %H:%M")
  
    rescue 
      @title = "did you forget?"
      @error = $!
      nil
    end

  end

  def error
    @title = "an error has occured"
  end

private

  def require_auth(type)
    response['WWW-Authenticate'] = %(Basic realm="Login Required")
    respond 'Unauthorized', 401 unless auth = request.env['HTTP_AUTHORIZATION'] and check_auth(type => auth)  
  end

  def check_auth(data)
    
    return false unless data[:student] or data[:professor]

    type, user = data.shift
    user, pw = user.split[1].unpack('m')[0].split(":")

    if type == :student
      user = Students[user]
      @current_id = ["student nr. "]
    elsif type == :professor
      user = Professors[user]
      @current_id = ["professor nr. "]
    else
      return false
    end

    if user and valid = user.valid(pw)
      @current_user = "You are logged in as #{user.name}"
      @current_id << user.id
    end

    valid

  end

end