
require "../config"
require "./abstract"

module Providers
  class SignalSpam < Abstract

    property config : Config? = nil

    def initialize
    end

    def process(email_content : String)
      load_config
      agent = Mechanize.new
      authenticate(agent)
      submit_spam_report(agent, email_content)
    end

    def create_config_file(username : String, password : String)
      auth = Authentication.new(username: username, password: password)
      config = Config.new(authentication: auth)
      config_path = File.expand_path("~/.config/bulkbarrage/config.yaml", home: ENV["HOME"])
      FileUtils.mkdir_p(File.dirname(config_path))
      File.write(config_path, config.to_yaml)
    end

    private def load_config
      config_path = File.expand_path("~/.config/bulkbarrage/config.yaml", home: ENV["HOME"])
      begin
        @config = Config.from_yaml(File.read(config_path))
      rescue ex
        puts "Error reading or parsing config file: #{ex.message}"
        exit(1)
      end
    end

    private def authenticate(agent)
      # Visiter la page de connexion pour obtenir le token d'authenticité
      login_page = agent.get("https://signalants.signal-spam.fr/login")
      form = login_page.forms.first
      authenticity_token = form.field_with("authenticity_token").value
      puts "Authentication page loaded."

      # Configurer les détails de l'utilisateur
      config = @config
      return if config.nil?

      form.field_with("user[email_or_login]").value = config.authentication.username
      form.field_with("user[password]").value = config.authentication.password
      # form.field_with("authenticity_token").value = authenticity_token

      # Soumettre le formulaire
      result_page = agent.submit(form)
      raise "Unable to authenticate" if result_page.nil?
      puts "Authenticated."

    end

    private def submit_spam_report(agent, email_spam : String)
      report_page = agent.get("https://signalants.signal-spam.fr/reportings/new")
      form = report_page.forms.first
      authenticity_token = form.field_with("authenticity_token").value
      puts "Reporting page loaded."

      form.field_with("reporting[raw_email]").value = email_spam
      result_page = agent.submit(form)
      raise "Unable to submit" if result_page.nil?
      puts "Reporting sent."
    end

  end
end
