module TagsHelper
  include StoresHelper
  include CoursesHelper
  # 通过 id和type获取对象
  def get_object(obj_id,obj_type)
    @obj = nil
    case obj_type
    when '1'
      @obj = User.find_by_id(obj_id)
    when '2'
      @obj = Project.find_by_id(obj_id)
    when '3'
      @obj = Issue.find_by_id(obj_id)
    when '4'
      @obj = Bid.find_by_id(obj_id)
      when '5'
        @obj = Forum.find_by_id(obj_id)
    when '6'
      @obj = Attachment.find_by_id(obj_id)
    when '7'
      @obj= Contest.find_by_id(obj_id)
    when '9'
      @obj= Course.find_by_id(obj_id)
    when '10'
      @obj = Attachment.find_by_id(obj_id)
    else
      raise Exception, '[TagsHelper] ===> tag type unknow.'
    end
    return @obj
  end
    
  # 判断登录用户是否可以对用户、项目、需求、问题中tag进行删除动作
  # 这里关于项目可以使用User.memeber_of?来做判断，这样可以提高该函数效率，但对满足需求有偏差
  # 返回值为true 或  false
  def can_remove_tag(user,obj_id,obj_type)
    @result = false
    case obj_type
    when '1'    # 对用户 是否是本人
       @obj = User.find_by_id(obj_id)
       if user == @obj
         @result = true
       end
    when '2'
      @result = is_manager?(user.id,obj_id)
    when '3'
      @project_id = Issue.find_by_id(obj_id)
      @result = is_manager?(user.id,@project_id)
    when '4'
      if user.id == obj_id
        @result = true
      end
      when '5'
        @result = is_forum_manager?(user.id,obj_id)
    when '7'
      if user.id == obj_id
        @result = true
      end
   when '9'
     @result = is_course_manager?(user.id,obj_id)
    end
    return @result
  end

end

#判断课程course中是否包含课件attachment，course中引用了attachment也算作包含
def course_contains_attachment? course,attachment
  course.attachments.each do |att|
    if att.id == attachment.id || (!att.copy_from.nil? && !attachment.copy_from.nil? && att.copy_from == attachment.copy_from) || att.copy_from == attachment.id || att.id == attachment.copy_from
      return true
    end
  end
  false
end

#判断用户是否拥有不包含当前资源的课程，需用户在该课程中角色为教师且该课程属于当前学期或下一学期
def has_course? user,file
  result = false
  user.courses.each do |course|
    if !course_contains_attachment?(course,file) && is_course_teacher(User.current,course) && course_in_current_or_next_term(course)
      return true
    end
  end
  result
end

# 判断用户是否是贴吧的管理员
# add by chenmin
def is_forum_manager?(user_id,forum_id)
  @result = false
  @user_id = Forum.find(forum_id).creator_id;
  if @user_id == user.id
    @result = true
  end
  return @result
end

def tagname_val
  ("#tag_name_name").value
end