class MailCron
  
  include Mongoid::Document
  include Mongoid::Timestamps
  

  field :mail_from_app
  field :mail_from 
  field :mail_to  
  field :mail_reply_to  
  field :mail_subject
  field :mail_content, :type => Hash
  field :mail_sentdate , :type => DateTime

  field :create_user_id
  field :update_user_id
  
  has_many :mail_cron_files, :autosave => true, :dependent => :destroy 

  accepts_nested_attributes_for :mail_cron_files, :allow_destroy => true 

  after_save :save_mail_cron_files


  def save_mail_cron_files
    self.mail_cron_files.each do |t|
      if t.should_destroy
        t.destroy
      end
    end
  end

  def self.get_send_group_mail(send_mails, other_send_mails = '')

    @group_mail = Array.new

    send_mails.each do |email_user_id|

      if !email_user_id.blank?

        @user = User.find(email_user_id)

        @group_mail << @user.email if !@user.blank?

      end

    end if !send_mails.blank?

    other_send_mails.split(",").collect do |oa|
      @group_mail <<  oa
    end if !other_send_mails.blank?

    @group_mail.uniq

  end

  def self.send_mail_now(mail_cron_id)

    mail_data = MailCron.find(mail_cron_id)

    if !mail_data.blank?

      @mail_j = 0
      @read_mails = Array.new 

      @mails = mail_data.mail_to.split(",")

      @mails.each do |send_mail|

        @read_mails << send_mail

        @mail_j += 1 

        if  0 == @mail_j % 30 
          MailCronMailer.cron_mail( mail_data.id, @read_mails.join(',') ).deliver
          @read_mails = Array.new

          sleep 10
        end

      end

      if !@read_mails.join(',').blank?
        MailCronMailer.cron_mail( mail_data.id, @read_mails.join(',') ).deliver
        @read_mails = Array.new

        sleep 10
      end  

    end  
    
  end

end