#!/usr/bin/env ruby
require "rubygems"
require "bundler/setup"
require "mailman"

Mailman.config.logger = Logger.new("log/mailman.log")

Mailman.config.ignore_stdin = true #ignore input from STDIN

Mailman.config.poll_interval = 20 # To poll for mails in every 5 seconds


# Email Configration for mailman
Mailman.config.pop3 = {
  server: ENV['SERVER_ADDRESS'], # example pop.example.com 
  port: 995, 
  ssl: true,
  username: ENV['USERNAME'],
  password: ENV['EMAIL_PASSWORD']
}

Mailman::Application.run do
  # routes are written here
  # route for mail having node with id in their subject will only be accepted for processing
  default do
# REMOVING ENTIRE 'begin/rescue' loop to try to address mailmain issues
#     begin
#       retries ||= 0
      # do something with the database that does not fetch mails yet (let's try to ensure we have a MySQL connection first)
      puts Comment.last.inspect
      Mailman.logger.info "Mail received from #{message.from.first}: '#{message.subject}' - '#{message&.html_part}'"
      if message.subject == "Incoming mail parsing test"
        Mailman.logger.info "Received incoming mail parsing test from #{message.from.first} at #{Time.now.to_s}"
      end
      last_comment = Comment.last
      comment_node_id = Comment.new_comment_from_email(message)
      if Comment.last.id != last_comment.id
        Mailman.logger.info "Comment created from #{message.from.first}: '#{message.subject}' - https://publiclab.org/n/#{comment_node_id}"
      end
#     rescue Exception => e
#       Mailman.logger.error "Exception occurred while receiving message:\n#{message}"
#       Mailman.logger.error [e, *e.backtrace].join("\n")
      # Seeing major site slowdowns; commenting out for now; 
      # https://github.com/publiclab/plots2/issues/5817
      # retry if (retries += 1) < 3
#     end
  end

end
