module Mobile
  module Entities
    class Attachment  < Grape::Entity
      include Redmine::I18n
      include ActionView::Helpers::NumberHelper
      include ApplicationHelper
      def self.attachment_expose(field)
        expose field do |f,opt|
          if f.is_a?(Hash) && f.key?(field)
            f[field]
          elsif f.is_a?(::Attachment)
            if f.respond_to?(field)
              if field == :created_on
                format_time(f.send(field))
              else
                f.send(field)
              end
            else
              case field
                when :file_dir
                  "attachments/download/" << f.send(:id).to_s << '/'
                when :attafile_size
                  (number_to_human_size(f.filesize)).gsub("ytes", "").to_s
                when :coursename
                  f.course.nil? ? "" : f.course.name
                when :syllabus_title
                  f.course.nil? ? "" : f.course.syllabus.nil? ? "" : f.course.syllabus.title
                when :course_id
                  f.course.nil? ? 0 : f.course.id

              end
            end
          end
        end
      end
      attachment_expose :id
      attachment_expose :filename
      attachment_expose :description
      attachment_expose :downloads
      attachment_expose :quotes
      attachment_expose :created_on
      attachment_expose :file_dir
      attachment_expose :attafile_size
      attachment_expose :coursename   #所属班级名
      attachment_expose :syllabus_title   #所属班级名
      attachment_expose :course_id   #所属班级名
      expose :current_user_is_teacher, if: lambda { |instance, options| options[:user] } do |instance, options|
        current_user = options[:user]
        current_user_is_teacher = false
        current_user_is_teacher = is_course_teacher(current_user,instance.course)
        current_user_is_teacher
      end
    end
  end
end