# this module retrieves all the data for a particular model from the DB
module TableDumper
  def self.get_data(model)
    # note that not all Users have email(eg guests)
    return case model
    when 'topic'
      Topic.find_by_sql("
      SELECT t.id, t.start_date, t.title, u.email expert_email
      FROM topics t, users u
      WHERE t.expert_id = u.id
      ORDER BY t.start_date
      ")
    when 'support_material'
      SupportMaterial.find_by_sql("
      SELECT s.id, s.name, s.url, s.filename, s.topic_id
      FROM support_materials s
      ORDER BY 1
      ")
    when 'participant'
      Participant.find_by_sql("
      SELECT u.user_number, u.email, u.created_at
      FROM users u
      WHERE u.type = 'Participant'
      ORDER BY u.user_number ASC
      ")
    when 'user'
      User.find_by_sql("
      SELECT u.user_number, u.email, u.created_at, u.id, u.type
      FROM users u
      ORDER BY u.type, u.user_number ASC
      ")
    when 'comment'
      Comment.find_by_sql("
      SELECT c.created_at, c.id, c.parent_id 'in_reply_to', c.topic_id, c.body, u.email 'user_email' 
      FROM comments c, users u
      WHERE c.created_by = u.id
      ORDER BY c.topic_id, c.root_id ASC, c.lft ASC")
    when 'rating'
      AbstractRating.find_by_sql("
      SELECT r.created_on created_at, r.type, r.subject_id, r.value, u.email 'user_email' 
      FROM ratings r, users u
      WHERE r.participant_id = u.id
      ORDER BY r.type, r.created_on
      ") # TODO rename created_on -> created_at to match other tables
         # consolidate different references to users (or document differences)
    when 'comment_reading'
      Reading.find_by_sql("
      SELECT r.created_at, u.email 'user_email', r.readable_id 'comment_id' 
      FROM readings r, users u
      WHERE r.participant_id = u.id AND r.readable_type = 'Comment'
      ORDER BY r.created_at ASC")
    when 'support_material_reading'
      Reading.find_by_sql("
      SELECT r.created_at, u.email 'user_email', r.readable_id 'support_material_id'
      FROM readings r, users u
      WHERE r.participant_id = u.id AND r.readable_type = 'SupportMaterial'
      ORDER BY r.created_at ASC")
    when 'all'
      raise NotImplementedError
    else
      raise ArgumentError, "unknown model"
    end
  end
  
end