# encoding: utf-8

class MailCronMailer < ActionMailer::Base 
  default :from => "orbit_test@rulingcom.com"
  
  def get_settings
    
    @site = Site.first

    @smtp_settings = {
      :address => @site['site_settings']['address'],
      :port => @site['site_settings']['port'],
      :domain => @site['site_settings']['domain'],
      :authentication => @site['site_settings']['authentication'],
      :enable_starttls_auto => @site['site_settings']['enable_starttls_auto']
    }

    if !@site['site_settings']['user_name'].blank? 
      @smtp_settings[:user_name] = @site['site_settings']['user_name']
    end

    if !@site['site_settings']['password'].blank? 
      @smtp_settings[:password] = @site['site_settings']['password']
    end 


    ActionMailer::Base.smtp_settings = @smtp_settings

  end


  def cron_mail( data_id, group_mail )
    
    get_settings

    @data = MailCron.find(data_id)

    if @data

      I18n.locale = @data.mail_content["lang"] if !@data.mail_content["lang"].blank?

      @mail_from = !@data.mail_from.blank? ? @data.mail_from : @site['site_settings']['service_email']

      @mail_reply_to = !@data.mail_reply_to.blank? ? @data.mail_reply_to : @site['site_settings']['reply_email']

      @user = User.find(@data.create_user_id)
      
      if !@data.mail_cron_files.blank?
        @data.mail_cron_files.each_with_index do |mail_cron_file, i|
          file_type = File.extname(mail_cron_file.file.to_s)
          file_content = Mongo::GridFileSystem.new(Mongoid.database).open(mail_cron_file.file.url.gsub("/gridfs/", "").force_encoding("UTF-8"), 'r')
          attachments["#{mail_cron_file.title}#{file_type}"] = file_content.read
        end 
      end

      if !@data.mail_content["text"].blank?
        mail( :from => "\"#{@site.title}\" <#{@mail_from}>", :reply_to => @mail_reply_to, :bcc => group_mail, :subject => @data.mail_subject ) do |format| 
          format.html { render :text => @data.mail_content["text"] } 
        end 
      elsif !@data.mail_content["template"].blank?
        mail( :from => "\"#{@site.title}\" <#{@mail_from}>", :reply_to => @mail_reply_to, :bcc => group_mail, :subject => @data.mail_subject ) do |format| 
          format.html { render :template => @data.mail_content["template"], :collection => @data.mail_content  } 
        end 
      end 


      @mail_cron_log = {  
        :mail_subject => @data.mail_subject,
        :mail_to => group_mail,
        :mail_user => "#{@user.name} <#{@user.email}>",
        :mailer_count => group_mail.split(",").size,
        :mail_from_app => @data.mail_from_app 
      } 

      @mail_cron_log = MailCronLog.new(@mail_cron_log) 


      @mail_cron_log.save

      @data.destroy

    end

  end

end