class SeminarSignupContribute

  include Mongoid::Document
  include Mongoid::Timestamps

  field :title
  field :abstract_number , type: String , default: ""
  field :presentation_type , type: String , default: ""
  field :sort_number , type: Integer, default: 10000
  mount_uploader :file, AssetUploader
  field :filename, type: String
  field :description
  field :preferred_session
  field :final_session
  belongs_to :seminar_signup
  has_one :seminar_review_result, dependent: :destroy
  accepts_nested_attributes_for :seminar_review_result
  has_many :seminar_submission_values, autosave: true, dependent: :destroy
  accepts_nested_attributes_for :seminar_submission_values, :allow_destroy => true
  scope :sort_ordered, ->{ order_by(:sort_number=>1,:created_at=>1) }
  after_destroy do
    seminar_signup = self.seminar_signup.reload rescue nil
    seminar_signup_id = seminar_signup.id.to_s
    seminar_submission_field_ids = seminar_signup.seminar_main.seminar_submission_fields.where(:markup=>"seminar_preferred_session").pluck(:id) rescue []
    if seminar_signup && seminar_submission_field_ids.count != 0
    	seminar_signup_contribute_ids = seminar_signup.seminar_signup_contributes.pluck(:id)
    	seminar_submission_values = SeminarSubmissionValue.where(:seminar_signup_contribute_id.in=>seminar_signup_contribute_ids,:seminar_submission_field_id.in=>seminar_submission_field_ids).to_a
    	seminar_sessions = seminar_signup.seminar_main.seminar_sessions.to_a
    	seminar_sessions.each do |ss|
    		ss.default_seminar_signup_ids.delete(seminar_signup_id)
    		ss.save(:validate=>false)
    	end
    	seminar_submission_value = seminar_submission_values.last
    	val = seminar_submission_value["val"].to_i rescue nil
    	unless val.nil?
	    	seminar_session = seminar_sessions.select{|ss| ss.key == val}.first
	    	if seminar_session
	    		seminar_session.default_seminar_signup_ids << seminar_signup_id
	    		seminar_session.save(:validate=>false)
	    	end
	    end
    end
  end
  before_save do
    self.update_filename
  end
  def update_filename
    if self.title.blank?
      self.filename = self.file.file.filename rescue ''
    else
      if self.file.file
        self.filename = self.title.sub(/#{::Regexp.escape(File.extname(self.title))}$/,'') + File.extname(self.file.file.filename)
      else
        self.filename = self.title
      end
    end
    self.filename
  end
  def disp_filename
    if self.filename.nil?
      self.class.where(:id=>self.id).update_all(:filename=>self.update_filename)
    end
    self.filename
  end
end