module JamRuby
  class EmailNewMusicianMatch

    PER_PAGE = 150
    LIMIT = 20
    JOINED_WITHIN_DAYS = 7
    ACTIVE_WITHIN_DAYS = 30
    
    PRIORITY_RECIPIENTS = %w(seth@jamkazam.com david@jamkazam.com peter@jamkazam.com nuwan@jamkazam.com).freeze

    def self.subject
      "New musicians with good Internet connections to you have joined JamKazam!"
    end

    def self.send_new_musicians
      
      params = {
        latency_good: true,
        latency_fair: true,
        latency_high: false,
        proficiency_beginner: true, 
        proficiency_intermediate: true, 
        proficiency_expert: true, 
        from_location: false,
        joined_within_days: JOINED_WITHIN_DAYS,
        active_within_days: ACTIVE_WITHIN_DAYS,
        limit: PER_PAGE
      }
      
      email_sending = UserMatchEmailSending.most_recent
      if email_sending.nil? || email_sending.completed?
        email_sending = UserMatchEmailSending.create
      end
      
      begin

        recipients = User.where("users.subscribe_email = ? AND 
          users.subscribe_email_for_user_match = ? 
          AND NOT COALESCE(users.user_match_email_sent_at, ?) > ?", 
          true, true, 7.days.ago, 6.days.ago).where.not(id: email_sending.sent_user_ids).order("
            CASE WHEN users.email IN ('#{PRIORITY_RECIPIENTS.map {|str| "\"#{str}\""}.join(',')}') 
            THEN 0 ELSE 1 END, last_active_at DESC").select("users.*, 
            GREATEST(updated_at, last_jam_updated_at) AS last_active_at").limit(LIMIT)
        
        AdminMailer.ugly({to: APP_CONFIG.user_match_monitoring_email,
          subject:"Weekly user match email sending job started.",
          body: "#{email_sending.sent_user_ids.any?? "This job is resuming. It was originally started at #{email_sending.created_at} and has been sent to #{email_sending.sent_user_ids.size} user(s) so far." : "This job was started at #{email_sending.created_at}" }. It will send to total of #{ recipients.size } users."}).deliver_now

          recipients.find_each do |user|
          
          ip_address = user.last_jam_addr.blank?? '127.0.0.1' : IPAddr.new(user.last_jam_addr, Socket::AF_INET).to_s
          matched_musician_data = []
          nextOffset = 0

          while !nextOffset.nil? && nextOffset >= 0 do
           
            params.merge!({ offset: nextOffset })

            results, latency_data, nextOffset = JamRuby::MusicianFilter.filter(user, ip_address, params)

            matched_musician_data << [{ musicians: results, latencies: latency_data }] if results && results.size > 0
          end

          if matched_musician_data.size > 0
            
            UserMailer.new_musicians_match(user, matched_musician_data).deliver_now 
            
            #user.update_column(:user_match_email_sent_at, Time.now)
            #email_sending.sent_user_ids.push(user.id)
            #email_sending.save!
          end
        end
        
        email_sending.total_recipients = email_sending.sent_user_ids.size
        email_sending.completed_at = Time.now
        email_sending.save!

        AdminMailer.ugly({
          to: APP_CONFIG.user_match_monitoring_email,
          subject:"Weekly user match email sending completed.",
          body: "Weekly email sending job was completed at #{Time.now}. It was sent to #{email_sending.sent_user_ids.size} user(s)."
        }).deliver_now

      rescue => exception
        begin
          fail_count = email_sending.fail_count
          email_sending.update_attributes(fail_count: fail_count + 1, exception_detail: exception.message)

          AdminMailer.ugly({to: APP_CONFIG.user_match_monitoring_email,
            subject:"Error occured when sending weekly user match email.",
            body: "An error was encountered at #{Time.now} while sending weekly user match email - #{exception.message}."}).deliver_now
        rescue
          Bugsnag.notify(exception)
        end
      end
    end

  end
end
