# encoding: utf-8
class SeminarSignup

  include Mongoid::Document
  include Mongoid::Timestamps

  field :sort_number , type: Integer, default: 10000

  field :status
  field :name # become Last Name for TICC
  field :tel, type: String # become First Name for TICC
  field :unit, localize: true
  field :phone, type: String
  field :fax, type: String
  field :email, type: String
  field :address, localize: true
  field :password
  field :note, localize: true
  field :serial_number
  field :final_session #only store old data , not used
  field :final_sessions
  field :preferred_sessions, type: Array, default: []
  belongs_to :seminar_main
  field :seminar_session_id #only store old data , not used
  field :seminar_session_ids, type: Array, default: []
  has_many :seminar_signup_values, :autosave => true, :dependent => :destroy
  has_many :seminar_signup_contributes, :autosave => true, :dependent => :destroy
  
  accepts_nested_attributes_for :seminar_signup_values, allow_destroy: true
  accepts_nested_attributes_for :seminar_signup_contributes, allow_destroy: true
  scope :sort_ordered, ->{ order_by(:sort_number=>1,:created_at=>1) }

  before_create do
    unit = self.unit_translations.values.select{|v| v.present?}.first
    self.unit_translations = I18n.available_locales.map{|l| [l.to_s,unit]}.to_h
    if self.serial_number.nil?
      s = SeminarMain.find(self.seminar_main)
      s.last_serial_number += 1
      self.serial_number = s.last_serial_number
    	s.save(:validate=>false)
    end
  end
  after_destroy do
    seminar_main = self.seminar_main
    if seminar_main.present?
      seminar_reviews = seminar_main.seminar_reviews
      id = self.id.to_s
      seminar_reviews.each do |sr|
        if sr.all_seminar_signup_ids.include?(id)
          sr.seminar_signup_ids.delete(id)
          sr.remove_seminar_signup_ids.delete(id)
          sr.default_seminar_signup_ids.delete(id)
          sr.save
        end
      end
      if seminar_main.unassigned_seminar_signup_ids.delete(id)
        seminar_main.save
      end
    end
    seminar_session = SeminarSession.where(:id=>self.seminar_session_id).first
    if seminar_session
      seminar_session.seminar_signup_ids.delete(self.id.to_s)
      seminar_session.save
    end
  end
  def display_serial_number
  	display_format_string(self.serial_number,4)
  end
  def display_format_string(num, str_length)
    return format("%0#{str_length}d", num)
  end
  def set_preferred_sessions
    self.preferred_sessions = self.seminar_signup_contributes.pluck(:preferred_session)
    self.save
  end
end
