defmodule Api.StudyMailer do
  import Swoosh.Email
  alias Api.EmailToSendContext
  alias Api.Mailer

  def create_mail(mail) do


    Envar.load(".env")
    Envar.require_env_file(".env")
    htmlbody = File.read(Envar.get("EMAIL_BODY_PATH"))
    |> elem(1)
    |> Solid.parse()
    |> elem(1)
    |> Solid.render!(
      %{"mail" =>
        %{"patientname" => mail.patientname |> String.replace("^", " "),
        "studydate" => mail.studydate,
        "patientid" => mail.patientid,
        "accessionnumber" => mail.accessionnumber,
        "idstudy" => mail.idstudy}
      })
    |> to_string()
    new()
      |> to({mail.patientname |> String.replace("^", " "), mail.patientemail |> String.trim |> String.replace(" ", "")})
      |> from({Envar.get("FROM"), Envar.get("SMTP_USER")})
      |> subject("Resultado del estudio")
      |> html_body(htmlbody)

 end

  def deliver_mail() do
    email = EmailToSendContext.get_next_email()
    if email do
      email_regex = ~r/[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/
      if String.match?(email.patientemail, email_regex) do
        emailtosendtest = create_mail(email)
        {res, term} = Mailer.deliver(emailtosendtest)
        case res do
          :ok ->
            EmailToSendContext.mark_sent(email.idemailtosend, %{sent: true, forcereprocess: false})
          :error ->
            EmailToSendContext.mark_sent(email.idemailtosend, %{errormsg: "Error", retries: email.retries + 1, forcereprocess: false})
            IO.inspect(res, label: "===> ERROR ======>")
            IO.inspect(term, label: "===> ERROR ======>")
          _ ->
            IO.inspect(res)
        end
      else
        EmailToSendContext.mark_sent(email.idemailtosend, %{errormsg: "Mail Incorrecto", retries: 10, forcereprocess: false})
      end
    else
      IO.puts("No hay estudios para enviar. Revisar que los mismos tengan un informe y mail correcto")
    end
  end
end
