defmodule Web.FeedController do
  use Web, :controller

  @feed_posts_count 50

  def feed(conn, _params) do
    posts =
      Core.Posts.get_published_recent_posts([:blog, :status], @feed_posts_count)

    updated =
      posts
      |> Enum.map(& &1.updated_at)
      |> Enum.max(NaiveDateTime)
      |> DateTime.from_naive!("Etc/UTC")

    feed =
      conn
      |> url(~p"/")
      |> Atomex.Feed.new(updated, "sloanelybutsurely.com")
      |> Atomex.Feed.author("Sloane", uri: url(conn, ~p"/"))
      |> Atomex.Feed.link(url(conn, ~p"/atom.xml"), rel: "self")
      |> Atomex.Feed.entries(Enum.map(posts, &entry/1))
      |> Atomex.Feed.build()
      |> Atomex.generate_document()

    conn
    |> put_resp_content_type("application/atom+xml")
    |> send_resp(200, feed)
  end

  defp entry(%Schema.Post{} = post) do
    permalink = Web.Paths.public_post_url(post)

    permalink
    |> Atomex.Entry.new(DateTime.from_naive!(post.updated_at, "Etc/UTC"), entry_title(post))
    |> Atomex.Entry.author("Sloane", uri: url(~p"/"))
    |> Atomex.Entry.published(DateTime.from_naive!(post.published_at, "Etc/UTC"))
    |> Atomex.Entry.link(permalink, rel: "alternate")
    |> Atomex.Entry.content({:cdata, Web.Markdown.to_html(post.body)}, type: "html")
    |> Atomex.Entry.build()
  end

  defp entry_title(%Schema.Post{kind: :blog, title: title}), do: title

  @status_title_length 40

  defp entry_title(%Schema.Post{kind: :status, body: body}) do
    if String.length(body) <= @status_title_length do
      body
    else
      (body
       |> String.slice(0, @status_title_length - 1)
       |> String.trim_trailing()) <> "…"
    end
  end
end