defmodule ApiWeb.EmailerLive.Index do
  use ApiWeb, :live_view

  alias Api.EmailToSendContext

  def mount(_params, _session, socket) do

  cols = [
    
    %{title: "id", field: "idemailtosend", headerFilter: true},
    %{title: "ID Study", field: "idstudy", headerFilter: true},
    %{title: "email", field: "patientemail", width: 300, headerFilter: true, editor: "input"},
    %{title: "sent", field: "sent", formatter: "tickCross", hozAlign: "center", editor: "tickCross", headerFilter: true},
    %{title: "hasreport", field: "hasreport", formatter: "tickCross", hozAlign: "center", headerFilter: true},
    %{title: "retries", field: "retries", headerFilter: true},
    %{title: "errormsg", field: "errormsg", width: 200},
    %{title: "forcereprocess", field: "forcereprocess", formatter: "tickCross", headerFilter: true},
    %{title: "Sent date time", field: "sentdatetime"},
    %{title: "Accession Number", field: "accessionnumber"},
    %{title: "Patientname", field: "patientname"},
    %{title: "Patient ID", field: "patientid"},
    %{title: "Study Date", field: "studydate"}
  ]
  socket =
    socket
    |> assign(%{
      columns: cols,
      current_row: %{}
     })
     {:ok, socket}
  end

  def data(email) do
  %{
    idemailtosend: email.idemailtosend,
    idstudy: email.idstudy,
    patientemail: email.patientemail,
    sent: email.sent,
    hasreport: email.hasreport,
    retries: email.retries,
    errormsg: email.errormsg,
    forcereprocess: email.forcereprocess,
    sentdatetime: email.sentdatetime,
    accessionnumber: email.accessionnumber,
    patientname: email.patientname,
    patientid: email.patientid,
    studydate: email.studydate
  }
  end

  def handle_event(msg, params, socket) do
    case msg do
      "fetch_data" ->
          emails =
            EmailToSendContext.list_emails(
            :paged,
            {params["filter"], params["sort"]},
            params["page"],
            25
        )
        res = %{last_page: emails.total_pages + 1, data: for(email <- emails.list, do: data(email))}
        {:reply, res, socket}
      "celledited" -> 
        case EmailToSendContext.update_emailtosend(params) do
          {:ok, _} -> {:noreply, socket |> put_flash(:info, "Actualizado correctamente")}
          _ ->{:noreply, socket |> put_flash(:error, "Error actualizando")}
        end 

      "rowSelected" -> 
        {:noreply, socket}

      "update_tabulator" ->
        {:noreply, push_event(socket, "update_tabulator", %{})}

      _ -> {:noreply, socket}

    end
  end

 end
