Don't show rating in text if rating was 0.

defmodule Slacktapped.Checkins do
  @instance_name System.get_env("INSTANCE_NAME") ||
    Application.get_env(:slacktapped, :instance_name)
  @redis Application.get_env(:slacktapped, :redis)

  @doc """
  Processes a checkin for use in a Slack post:

  1. Verifies the checkin is eligible to post.
  2. Parses the checkin to a Slack attachment.
  3. Adds the attachment to the checkin.
  4. Reports the checkin post to Redis.
  """
  def process_checkin(checkin) do
    with {:ok, checkin} <- is_eligible_checkin_post(checkin),
         {:ok, attachment} <- parse_checkin(checkin),
         {:ok, checkin} <- Slacktapped.add_attachment({:ok, attachment}, checkin),
         {:ok, checkin} <- report_checkin_type({:ok, checkin}),
         do: {:ok, checkin}
  end

  @doc """
  Determines if a checkin is eligible to be posted to Slack.

  Checkin is ineligible to post if:

  1. There is a Redis key indicating that this checkin was posted under this
     instance, and had an image with it.
  2. There is a Redis key indicating that this checkin was posted under this
     instance, and had no image with it, but the checkin we see now still does
     not have an image.

  ## Examples

  A checkin that was not already posted:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{"checkin_id" => 9985})
      {:ok, %{"checkin_id" => 9985}}

  A checkin that was already posted, and had an image:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{"checkin_id" => 9988})
      {:error, %{"checkin_id" => 9988}}

  A checkin that was already posted and had no image, and we do not currently
  have an image:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{"beer" => %{}, "checkin_id" => 5566})
      {:error, %{"beer" => %{}, "checkin_id" => 5566}}

  A checkin that was already posted and had no image, and we now have an
  image:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{
      ...>   "beer" => %{},
      ...>   "checkin_id" => 5566,
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> })
      {:ok, %{
        "beer" => %{},
        "checkin_id" => 5566,
        "media" => %{
          "items" => [
            %{
              "photo" => %{
                "photo_id" => 987,
                "photo_img_lg" => "http://path/to/beer/image"
              }
            }
          ]
        }
      }}

  """
  def is_eligible_checkin_post(checkin) do
    checkin_id = checkin["checkin_id"] || ""
    media_items = checkin["media"]["items"]
    has_image = is_list(media_items) and Enum.count(media_items) >= 1
    get_key = "GET #{@instance_name}:#{checkin_id}"

    cond do
      @redis.command("#{get_key}:with-image") == {:ok, "1"} ->
        {:error, checkin}
      @redis.command("#{get_key}:without-image") == {:ok, "1"} and not has_image ->
        {:error, checkin}
      true ->
        {:ok, checkin}
    end
  end

  @doc ~S"""
  Parses a checkin into an attachment for Slack.

  ## Examples

  A typical checkin with a rating and comment:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "user" => %{
      ...>     "user_name" => "nicksergeant",
      ...>     "user_avatar" => "http://path/to/user/avatar"
      ...>   },
      ...>   "beer" => %{
      ...>     "bid" => 123,
      ...>     "beer_abv" => 4.5,
      ...>     "beer_label" => "http://path/to/beer/label",
      ...>     "beer_name" => "IPA",
      ...>     "beer_slug" => "two-lake-ipa",
      ...>     "beer_style" => "American IPA"
      ...>   },
      ...>   "brewery" => %{
      ...>     "brewery_id" => 1,
      ...>     "brewery_label" => "http://path/to/brewery/label",
      ...>     "brewery_name" => "Two Lake"
      ...>   },
      ...>   "checkin_comment" => "Lovely!",
      ...>   "checkin_id" => 567,
      ...>   "rating_score" => 3.5
      ...> })
      {:ok,
        %{
          "author_icon" => "http://path/to/user/avatar",
          "author_link" => "https://untappd.com/user/nicksergeant",
          "author_name" => "nicksergeant",
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/1|Two Lake>",
          "footer_icon" => "http://path/to/brewery/label",
          "image_url" => "http://path/to/beer/label",
          "text" => "" <>
            "<https://untappd.com/user/nicksergeant|nicksergeant> is drinking " <>
            "<https://untappd.com/b/two-lake-ipa/123|IPA> " <>
            "(American IPA, 4.5% ABV)." <>
            "\nThey rated it a 3.5 and said \"Lovely!\"\n" <>
            "<https://untappd.com/user/nicksergeant/checkin/567|Toast »>",
          "title" => "IPA",
          "title_link" => "https://untappd.com/b/two-lake-ipa/123"
        }
      }

  A checkin without a rating:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "checkin_comment" => "Lovely!"
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV)." <>
            "\nThey said \"Lovely!\"\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin without a comment:

      iex> Slacktapped.Checkins.parse_checkin(%{"rating_score" => 1.5})
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV)." <>
            "\nThey rated it a 1.5.\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin without a comment or rating:

      iex> Slacktapped.Checkins.parse_checkin(%{})
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with a rating of 0:

      iex> Slacktapped.Checkins.parse_checkin(%{"rating_score" => 0})
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with an image:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => "http://path/to/beer/image",
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with a venue:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "venue" => %{
      ...>     "venue_id" => 789,
      ...>     "venue_name" => "Venue Name",
      ...>     "venue_slug" => "venue-slug"
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV) " <>
            "at <https://untappd.com/v/venue-slug/789|Venue Name>.\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with an image, with a previously-posted checkin with no image:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "checkin_id" => 5566,
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => "http://path/to/beer/image",
          "text" => "" <>
            "<https://untappd.com/user/|> added an image to " <>
            "<https://untappd.com/user//checkin/5566|their checkin> of " <>
            "<https://untappd.com/b//|>.",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  The default Untappd beer label is ignored:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "beer" => %{
      ...>     "beer_label" => "https://untappd.akamaized.net/site/assets/images/temp/badge-beer-default.png"
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => "",
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  """
  def parse_checkin(checkin) do
    {:ok, user_name} = Slacktapped.parse_name(checkin["user"])

    beer_abv = checkin["beer"]["beer_abv"]
    beer_id = checkin["beer"]["bid"]
    beer_label = checkin["beer"]["beer_label"]
    beer_name = checkin["beer"]["beer_name"]
    beer_slug = checkin["beer"]["beer_slug"]
    beer_style = checkin["beer"]["beer_style"]
    brewery_id = checkin["brewery"]["brewery_id"]
    brewery_name = checkin["brewery"]["brewery_name"]
    brewery_label = checkin["brewery"]["brewery_label"]
    checkin_comment = checkin["checkin_comment"]
    checkin_id = checkin["checkin_id"]
    checkin_rating = checkin["rating_score"]
    media_items = checkin["media"]["items"]
    user_avatar = checkin["user"]["user_avatar"]
    user_username = checkin["user"]["user_name"]

    beer = "<https://untappd.com/b/#{beer_slug}/#{beer_id}|#{beer_name}>"
    toast = "<https://untappd.com/user/#{user_username}/checkin/#{checkin_id}|Toast »>"
    user = "<https://untappd.com/user/#{user_username}|#{user_name}>"

    rating_and_comment = cond do
      is_binary(checkin_comment)
        and checkin_comment != ""
        and is_number(checkin_rating) ->
          "\nThey rated it a #{checkin_rating} and said \"#{checkin_comment}\""
      is_binary(checkin_comment)
        and checkin_comment != "" ->
          "\nThey said \"#{checkin_comment}\""
      is_number(checkin_rating) and checkin_rating > 0 ->
        "\nThey rated it a #{checkin_rating}."
      true -> ""
    end

    venue = if is_map(checkin["venue"]) do
      venue_id = checkin["venue"]["venue_id"]
      venue_name = checkin["venue"]["venue_name"]
      venue_slug = checkin["venue"]["venue_slug"]
      " at <https://untappd.com/v/#{venue_slug}/#{venue_id}|#{venue_name}>"
    end

    image_url = cond do
      is_list(media_items) and Enum.count(media_items) >= 1 ->
        media_items
          |> Enum.at(0)
          |> get_in(["photo", "photo_img_lg"])
      beer_label != "https://untappd.akamaized.net/site/assets/images/temp/badge-beer-default.png" ->
        beer_label
      true -> ""
    end

    # If we have an image and there was already a post for this checkin
    # *without* an image, only indicate that an image was added.
    cmd = "GET #{@instance_name}:#{checkin_id}:without-image"
    text = if is_binary(image_url) and
        @redis.command(cmd) == {:ok, "1"} do
      "#{user} added an image to " <>
      "<https://untappd.com/user/#{user_username}/checkin/#{checkin_id}|" <>
      "their checkin> of #{beer}."
    else
      "#{user} is drinking #{beer} (#{beer_style}, #{beer_abv}% ABV)" <>
      "#{venue}.#{rating_and_comment}\n#{toast}"
    end

    {:ok, %{
      "author_icon" => user_avatar,
      "author_link" => "https://untappd.com/user/#{user_username}",
      "author_name" => user_username,
      "color" => "#FFCF0B",
      "fallback" => "Image of this checkin.",
      "footer" => "<https://untappd.com/brewery/#{brewery_id}|#{brewery_name}>",
      "footer_icon" => brewery_label,
      "image_url" => image_url,
      "text" => text,
      "title" => beer_name,
      "title_link" => "https://untappd.com/b/#{beer_slug}/#{beer_id}"
    }}
  end

  @doc """
  Reports that a checkin was posted to Slack by setting a Redis key. There are
  two possible Redis keys indicating a post was made:

  1. <slacktapped-instance-name>:<checkin_id>:with-image
  2. <slacktapped-instance-name>:<checkin_id>:without-image

  Already-posted checkins that were previously posted without an image are
  posted again indicating that the user added an image to the checkin. If a
  record exists for the checkin with an image, the checkin is not posted again.

  Examples

      iex> Slacktapped.Checkins.report_checkin_type({:ok, %{}})
      {:ok, %{"reported_as" => "without-image"}}

      iex> Slacktapped.Checkins.report_checkin_type({:ok, %{
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> }})
      {:ok, %{
        "reported_as" => "with-image",
        "media" => %{
          "items" => [
            %{
              "photo" => %{
                "photo_id" => 987,
                "photo_img_lg" => "http://path/to/beer/image"
              }
            }
          ]
        }
      }}

  """
  def report_checkin_type({:ok, checkin}) do
    checkin_id = checkin["checkin_id"]
    media_items = checkin["media"]["items"]
    has_image = is_list(media_items) and Enum.count(media_items) >= 1

    reported_as = cond do
      has_image == true ->
        @redis.command("SET #{@instance_name}:#{checkin_id}:with-image 1")
        "with-image"
      true ->
        @redis.command("SET #{@instance_name}:#{checkin_id}:without-image 1")
        "without-image"
    end

    checkin = Map.put(checkin, "reported_as", reported_as)

    {:ok, checkin}
  end
end

defmodule Slacktapped.Checkins do
  @instance_name System.get_env("INSTANCE_NAME") ||
    Application.get_env(:slacktapped, :instance_name)
  @redis Application.get_env(:slacktapped, :redis)

  @doc """
  Processes a checkin for use in a Slack post:

  1. Verifies the checkin is eligible to post.
  2. Parses the checkin to a Slack attachment.
  3. Adds the attachment to the checkin.
  4. Reports the checkin post to Redis.
  """
  def process_checkin(checkin) do
    with {:ok, checkin} <- is_eligible_checkin_post(checkin),
         {:ok, attachment} <- parse_checkin(checkin),
         {:ok, checkin} <- Slacktapped.add_attachment({:ok, attachment}, checkin),
         {:ok, checkin} <- report_checkin_type({:ok, checkin}),
         do: {:ok, checkin}
  end

  @doc """
  Determines if a checkin is eligible to be posted to Slack.

  Checkin is ineligible to post if:

  1. There is a Redis key indicating that this checkin was posted under this
     instance, and had an image with it.
  2. There is a Redis key indicating that this checkin was posted under this
     instance, and had no image with it, but the checkin we see now still does
     not have an image.

  ## Examples

  A checkin that was not already posted:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{"checkin_id" => 9985})
      {:ok, %{"checkin_id" => 9985}}

  A checkin that was already posted, and had an image:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{"checkin_id" => 9988})
      {:error, %{"checkin_id" => 9988}}

  A checkin that was already posted and had no image, and we do not currently
  have an image:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{"beer" => %{}, "checkin_id" => 5566})
      {:error, %{"beer" => %{}, "checkin_id" => 5566}}

  A checkin that was already posted and had no image, and we now have an
  image:

      iex> Slacktapped.Checkins.is_eligible_checkin_post(%{
      ...>   "beer" => %{},
      ...>   "checkin_id" => 5566,
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> })
      {:ok, %{
        "beer" => %{},
        "checkin_id" => 5566,
        "media" => %{
          "items" => [
            %{
              "photo" => %{
                "photo_id" => 987,
                "photo_img_lg" => "http://path/to/beer/image"
              }
            }
          ]
        }
      }}

  """
  def is_eligible_checkin_post(checkin) do
    checkin_id = checkin["checkin_id"] || ""
    media_items = checkin["media"]["items"]
    has_image = is_list(media_items) and Enum.count(media_items) >= 1
    get_key = "GET #{@instance_name}:#{checkin_id}"

    cond do
      @redis.command("#{get_key}:with-image") == {:ok, "1"} ->
        {:error, checkin}
      @redis.command("#{get_key}:without-image") == {:ok, "1"} and not has_image ->
        {:error, checkin}
      true ->
        {:ok, checkin}
    end
  end

  @doc ~S"""
  Parses a checkin into an attachment for Slack.

  ## Examples

  A typical checkin with a rating and comment:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "user" => %{
      ...>     "user_name" => "nicksergeant",
      ...>     "user_avatar" => "http://path/to/user/avatar"
      ...>   },
      ...>   "beer" => %{
      ...>     "bid" => 123,
      ...>     "beer_abv" => 4.5,
      ...>     "beer_label" => "http://path/to/beer/label",
      ...>     "beer_name" => "IPA",
      ...>     "beer_slug" => "two-lake-ipa",
      ...>     "beer_style" => "American IPA"
      ...>   },
      ...>   "brewery" => %{
      ...>     "brewery_id" => 1,
      ...>     "brewery_label" => "http://path/to/brewery/label",
      ...>     "brewery_name" => "Two Lake"
      ...>   },
      ...>   "checkin_comment" => "Lovely!",
      ...>   "checkin_id" => 567,
      ...>   "rating_score" => 3.5
      ...> })
      {:ok,
        %{
          "author_icon" => "http://path/to/user/avatar",
          "author_link" => "https://untappd.com/user/nicksergeant",
          "author_name" => "nicksergeant",
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/1|Two Lake>",
          "footer_icon" => "http://path/to/brewery/label",
          "image_url" => "http://path/to/beer/label",
          "text" => "" <>
            "<https://untappd.com/user/nicksergeant|nicksergeant> is drinking " <>
            "<https://untappd.com/b/two-lake-ipa/123|IPA> " <>
            "(American IPA, 4.5% ABV)." <>
            "\nThey rated it a 3.5 and said \"Lovely!\"\n" <>
            "<https://untappd.com/user/nicksergeant/checkin/567|Toast »>",
          "title" => "IPA",
          "title_link" => "https://untappd.com/b/two-lake-ipa/123"
        }
      }

  A checkin without a rating:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "checkin_comment" => "Lovely!"
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV)." <>
            "\nThey said \"Lovely!\"\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin without a comment:

      iex> Slacktapped.Checkins.parse_checkin(%{"rating_score" => 1.5})
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV)." <>
            "\nThey rated it a 1.5.\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin without a comment or rating:

      iex> Slacktapped.Checkins.parse_checkin(%{})
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with an image:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => "http://path/to/beer/image",
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with a venue:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "venue" => %{
      ...>     "venue_id" => 789,
      ...>     "venue_name" => "Venue Name",
      ...>     "venue_slug" => "venue-slug"
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => nil,
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV) " <>
            "at <https://untappd.com/v/venue-slug/789|Venue Name>.\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  A checkin with an image, with a previously-posted checkin with no image:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "checkin_id" => 5566,
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => "http://path/to/beer/image",
          "text" => "" <>
            "<https://untappd.com/user/|> added an image to " <>
            "<https://untappd.com/user//checkin/5566|their checkin> of " <>
            "<https://untappd.com/b//|>.",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  The default Untappd beer label is ignored:

      iex> Slacktapped.Checkins.parse_checkin(%{
      ...>   "attachments" => [],
      ...>   "beer" => %{
      ...>     "beer_label" => "https://untappd.akamaized.net/site/assets/images/temp/badge-beer-default.png"
      ...>   }
      ...> })
      {:ok,
        %{
          "author_icon" => nil,
          "author_link" => "https://untappd.com/user/",
          "author_name" => nil,
          "color" => "#FFCF0B",
          "fallback" => "Image of this checkin.",
          "footer" => "<https://untappd.com/brewery/|>",
          "footer_icon" => nil,
          "image_url" => "",
          "text" => "" <>
            "<https://untappd.com/user/|> is drinking " <>
            "<https://untappd.com/b//|> (, % ABV).\n" <>
            "<https://untappd.com/user//checkin/|Toast »>",
          "title" => nil,
          "title_link" => "https://untappd.com/b//"
        }
      }

  """
  def parse_checkin(checkin) do
    {:ok, user_name} = Slacktapped.parse_name(checkin["user"])

    beer_abv = checkin["beer"]["beer_abv"]
    beer_id = checkin["beer"]["bid"]
    beer_label = checkin["beer"]["beer_label"]
    beer_name = checkin["beer"]["beer_name"]
    beer_slug = checkin["beer"]["beer_slug"]
    beer_style = checkin["beer"]["beer_style"]
    brewery_id = checkin["brewery"]["brewery_id"]
    brewery_name = checkin["brewery"]["brewery_name"]
    brewery_label = checkin["brewery"]["brewery_label"]
    checkin_comment = checkin["checkin_comment"]
    checkin_id = checkin["checkin_id"]
    checkin_rating = checkin["rating_score"]
    media_items = checkin["media"]["items"]
    user_avatar = checkin["user"]["user_avatar"]
    user_username = checkin["user"]["user_name"]

    beer = "<https://untappd.com/b/#{beer_slug}/#{beer_id}|#{beer_name}>"
    toast = "<https://untappd.com/user/#{user_username}/checkin/#{checkin_id}|Toast »>"
    user = "<https://untappd.com/user/#{user_username}|#{user_name}>"

    rating_and_comment = cond do
      is_binary(checkin_comment)
        and checkin_comment != ""
        and is_number(checkin_rating) ->
          "\nThey rated it a #{checkin_rating} and said \"#{checkin_comment}\""
      is_binary(checkin_comment)
        and checkin_comment != "" ->
          "\nThey said \"#{checkin_comment}\""
      is_number(checkin_rating) ->
        "\nThey rated it a #{checkin_rating}."
      true -> ""
    end

    venue = if is_map(checkin["venue"]) do
      venue_id = checkin["venue"]["venue_id"]
      venue_name = checkin["venue"]["venue_name"]
      venue_slug = checkin["venue"]["venue_slug"]
      " at <https://untappd.com/v/#{venue_slug}/#{venue_id}|#{venue_name}>"
    end

    image_url = cond do
      is_list(media_items) and Enum.count(media_items) >= 1 ->
        media_items
          |> Enum.at(0)
          |> get_in(["photo", "photo_img_lg"])
      beer_label != "https://untappd.akamaized.net/site/assets/images/temp/badge-beer-default.png" ->
        beer_label
      true -> ""
    end

    # If we have an image and there was already a post for this checkin
    # *without* an image, only indicate that an image was added.
    cmd = "GET #{@instance_name}:#{checkin_id}:without-image"
    text = if is_binary(image_url) and
        @redis.command(cmd) == {:ok, "1"} do
      "#{user} added an image to " <>
      "<https://untappd.com/user/#{user_username}/checkin/#{checkin_id}|" <>
      "their checkin> of #{beer}."
    else
      "#{user} is drinking #{beer} (#{beer_style}, #{beer_abv}% ABV)" <>
      "#{venue}.#{rating_and_comment}\n#{toast}"
    end

    {:ok, %{
      "author_icon" => user_avatar,
      "author_link" => "https://untappd.com/user/#{user_username}",
      "author_name" => user_username,
      "color" => "#FFCF0B",
      "fallback" => "Image of this checkin.",
      "footer" => "<https://untappd.com/brewery/#{brewery_id}|#{brewery_name}>",
      "footer_icon" => brewery_label,
      "image_url" => image_url,
      "text" => text,
      "title" => beer_name,
      "title_link" => "https://untappd.com/b/#{beer_slug}/#{beer_id}"
    }}
  end

  @doc """
  Reports that a checkin was posted to Slack by setting a Redis key. There are
  two possible Redis keys indicating a post was made:

  1. <slacktapped-instance-name>:<checkin_id>:with-image
  2. <slacktapped-instance-name>:<checkin_id>:without-image

  Already-posted checkins that were previously posted without an image are
  posted again indicating that the user added an image to the checkin. If a
  record exists for the checkin with an image, the checkin is not posted again.

  Examples

      iex> Slacktapped.Checkins.report_checkin_type({:ok, %{}})
      {:ok, %{"reported_as" => "without-image"}}

      iex> Slacktapped.Checkins.report_checkin_type({:ok, %{
      ...>   "media" => %{
      ...>     "items" => [
      ...>       %{
      ...>         "photo" => %{
      ...>           "photo_id" => 987,
      ...>           "photo_img_lg" => "http://path/to/beer/image"
      ...>         }
      ...>       }
      ...>     ]
      ...>   }
      ...> }})
      {:ok, %{
        "reported_as" => "with-image",
        "media" => %{
          "items" => [
            %{
              "photo" => %{
                "photo_id" => 987,
                "photo_img_lg" => "http://path/to/beer/image"
              }
            }
          ]
        }
      }}

  """
  def report_checkin_type({:ok, checkin}) do
    checkin_id = checkin["checkin_id"]
    media_items = checkin["media"]["items"]
    has_image = is_list(media_items) and Enum.count(media_items) >= 1

    reported_as = cond do
      has_image == true ->
        @redis.command("SET #{@instance_name}:#{checkin_id}:with-image 1")
        "with-image"
      true ->
        @redis.command("SET #{@instance_name}:#{checkin_id}:without-image 1")
        "without-image"
    end

    checkin = Map.put(checkin, "reported_as", reported_as)

    {:ok, checkin}
  end
end


Remove trailing whitespace

Remove trailing whitespace

defmodule ExTwiml do
  @moduledoc """
  Contains macros to make generating TwiML from Elixir far easier and more
  efficient. Just `import ExTwiml` and go!

  ## Examples

  How to generate nested verbs, such as `<Gather>`:

      # Options are passed before "do"
      gather digits: 1, finish_on_key: "#" do
        # More verbs here ...
      end

      # Generates
      <Gather digits="1" finishOnKey="#"></Gather>

  How to generate simpler verbs, such as `<Say>`:

      # Options are passed as the second argument
      say "words to say", voice: "woman"

      # Generates
      <Say voice="woman">words to say</Say>

  How to generate command verbs, like `<Leave>` or `<Pause>`:

      # If the verb has no attributes, just write the name
      # of the verb:
      leave

      # Generates
      <Leave />

      # If the verb has attributes, like <Pause>, write them
      # after the name of the verb:
      pause length: 5

      # Generates
      <Pause length="5" />

  A complete example:

      import ExTwiml

      twiml do
        play "/assets/welcome.mp3"
        gather digits: 1 do
          say "For more menus, please press 1.", voice: "woman"
          say "To speak with a real person, please press 2.", voice: "woman"
        end
      end

  Produces the following `string`:

      <?xml version="1.0" encoding="UTF-8"?>
      <Response>
        <Play>/assets/welcome.mp3</Play>
        <Gather digits="3">
          <Say voice="woman">For more menus, please press 1.</Say>
          <Say voice="woman">To speak with a real person, please press 2.</Say>
        </Gather>
      </Response>

  You'd then need to render this string to the browser.
  """

  import ExTwiml.Utilities

  alias ExTwiml.ReservedNameError

  @verbs [
    # Nested
    :gather, :dial, :message,

    # Non-nested
    :say, :number, :play, :sms, :sip, :client, :conference, :queue, :enqueue,
    :leave, :hangup, :reject, :pause, :record, :redirect, :body, :media
  ]

  @doc """
  Start creating a TwiML document. Returns the rendered TwiML as a string.
  See the `ExTwiml` documentation to see how to call TwiML verbs from within
  the `twiml/1` macro.

  ## Example

      iex> import ExTwiml
      ...> twiml do
      ...>   say "Hello World"
      ...> end
      "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><Response><Say>Hello World</Say></Response>"
  """
  defmacro twiml(do: block) do
    quote do
      header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"

      # Create an Agent to store the buffer results, using var! to allow us to
      # continue to be able to update the buffer through multiple macros.
      #
      # The buffer's state is a list of XML fragments. New fragments are
      # inserted by other macros. Finally, all the fragments are joined
      # together in a string.
      {:ok, var!(buffer, Twiml)} = start_buffer([header])

      # Wrap the whole block in a <Response> tag
      tag :response do
        # Postwalk the AST, expanding all of the TwiML verbs into proper
        # `tag` and `text` macros. This gives the impression that there
        # is a macro for each verb, when in fact it all expands to only
        # two macros.
        unquote(block
                |> Macro.prewalk(&prewalk(&1, __CALLER__.file))
                |> Macro.postwalk(&postwalk/1))
      end

      xml  = render(var!(buffer, Twiml))      # Convert buffer to string
      :ok  = stop_buffer(var!(buffer, Twiml)) # Kill the Agent

      xml # Return our pretty TwiML!
    end
  end

  @doc """
  Use this macro to generate a tag not yet supported by this Twiml library. Note
  that you'll also need to use the `text` macro to include text within this tag.

  ## Examples

      tag :mms, to: "1112223333", from: "2223334444" do
        text "How are you doing?"
      end

  Will produce the following Twiml:

      <Mms to="1112223333" from="2223334444">How are you doing?</Mms>
  """
  defmacro tag(name, options \\ [], do: inner) do
    quote do
      put_buffer var!(buffer, Twiml), create_tag(:opening, unquote(name), unquote(options))
      unquote(inner)
      put_buffer var!(buffer, Twiml), create_tag(:closing, unquote(name))
    end
  end

  @doc """
  Adds whatever text is given to the current Twiml buffer, unmodified. As a
  result, this macro is really only useful when nested inside one of the other
  macros provided by this module.
  """
  defmacro text(string) do
    quote do
      put_buffer var!(buffer, Twiml), to_string(unquote(string))
    end
  end

  @doc "Start an Agent to store a given buffer state."
  @spec start_buffer(list) :: {:ok, pid}
  def start_buffer(state), do: Agent.start_link(fn -> state end)

  @doc "Stop a buffer."
  @spec stop_buffer(pid) :: atom
  def stop_buffer(buff), do: Agent.stop(buff)

  @doc "Update the buffer by pushing a new tag onto the beginning."
  @spec put_buffer(pid, any) :: atom
  def put_buffer(buff, content), do: Agent.update(buff, &[content | &1])

  @doc "Get the current state of a buffer."
  @spec get_buffer(pid) :: list
  def get_buffer(buff), do: Agent.get(buff, &(&1)) |> Enum.reverse

  @doc "Render the contents of the buffer into a string."
  @spec render(pid) :: String.t
  def render(buff), do: Agent.get(buff, &(&1)) |> Enum.reverse |> Enum.join

  ##
  # Private API
  ##

  # Check function definitions for reserved variable names
  defp prewalk({:fn, _, [{:-> , _, [[vars], _]}]} = ast, file_name) do
    assert_no_verbs!(vars, file_name)
    ast
  end

  defp prewalk(ast, _file_name), do: ast

  # {:text, [], ["Hello World"]}
  defp postwalk({:text, _meta, [string]}) do
    # Just add the text to the buffer. Nothing else needed.
    quote do: put_buffer(var!(buffer, Twiml), to_string(unquote(string)))
  end

  # {:gather, [], [[do: inner]]}
  defp postwalk({verb, _meta, [[do: inner]]}) when verb in @verbs do
    compile_nested(verb, [], inner)
  end

  # {:gather, [], [finish_on_key: "#", [do: inner]]}
  defp postwalk({verb, _meta, [options, [do: inner]]}) when verb in @verbs do
    compile_nested(verb, options, inner)
  end

  # {:say, [], ["Hello World", [voice: "woman"]}
  defp postwalk({verb, _meta, [string, options]}) when verb in @verbs and is_list(options) do
    compile_simple(verb, string, options)
  end

  # {:pause, [], [[length: 5]]}
  defp postwalk({verb, _meta, [options]}) when verb in @verbs and is_list(options) do
    compile_empty(verb, options)
  end

  # {:say, [], ["Hello World"]}
  # {:say, [], ["Hello #{var}"]} (String interpolation)
  defp postwalk({verb, _meta, [string]}) when verb in @verbs do
    compile_simple(verb, string)
  end

  # {:leave, [], Elixir}
  defp postwalk({verb, _meta, _args}) when verb in @verbs do
    compile_empty(verb)
  end

  # Don't modify any other ASTs.
  defp postwalk(ast), do: ast

  # For nested verbs, such as <Gather>
  defp compile_nested(verb, options, inner) do
    quote do
      tag unquote(verb), unquote(options) do
        unquote(inner)
      end
    end
  end

  # For simple verbs, such as <Say>
  defp compile_simple(verb, string, options \\ []) do
    quote do
      tag unquote(verb), unquote(options) do
        text unquote(string)
      end
    end
  end

  # For verbs without content, like <Leave> or <Pause>
  defp compile_empty(verb, options \\ []) do
    quote do
      # Render only a single tag, with options
      put_buffer var!(buffer, Twiml), create_tag(:self_closed, unquote(verb), unquote(options))
    end
  end

  defp assert_no_verbs!({name, _, _} = var, file_name)
  when is_atom(name) and name in @verbs do
    raise ReservedNameError, [var, file_name]
  end

  defp assert_no_verbs!(vars, file_name) when is_tuple(elem(vars, 0)) do
    vars
    |> Tuple.to_list
    |> Enum.each(&assert_no_verbs!(&1, file_name))
  end

  defp assert_no_verbs!(vars, _file_name), do: vars
end


Note that handlers are run by monitor processes (#86)

defmodule Honeydew do
  @moduledoc """
  A pluggable job queue + worker pool for Elixir.
  """

  alias Honeydew.Job
  alias Honeydew.JobMonitor
  alias Honeydew.Worker
  alias Honeydew.WorkerStarter
  alias Honeydew.WorkerGroupSupervisor
  alias Honeydew.Queue
  alias Honeydew.{Queues, Workers}
  require Logger

  @type mod_or_mod_args :: module | {module, args :: term}
  @type queue_name :: String.t | atom | {:global, String.t | atom}
  @type supervisor_opts :: Keyword.t
  @type async_opt :: {:reply, true} | {:delay_secs, pos_integer()}
  @type task :: {atom, [arg :: term]}
  @type filter :: (Job.t -> boolean) | atom

  @typedoc """
  Result of a `Honeydew.Job`
  """
  @type result :: term

  #
  # Parts of this module were lovingly stolen from
  # https://github.com/elixir-lang/elixir/blob/v1.3.2/lib/elixir/lib/task.ex#L320
  #

  @doc """
  Runs a task asynchronously.

  Raises a `RuntimeError` if `queue` process is not available.

  You can provide any of the following `opts`:

  - `reply`: returns the result of the job via `yield/1`, see below.
  - `delay_secs`: delays the execution of the job by the provided number of seconds.

  ## Examples

  To run a task asynchronously:

      Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue)

  To run a task asynchronously and wait for result:

      # Without pipes
      job = Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue, reply: true)
      Honeydew.yield(job)

      # With pipes
      :pong =
        {:ping, ["127.0.0.1"]}
        |> Honeydew.async(:my_queue, reply: true)
        |> Honeydew.yield()

  To run a task an hour later:

      Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue, delay_secs: 60*60)
  """
  @spec async(task, queue_name, [async_opt]) :: Job.t | no_return
  def async(task, queue, opts \\ []) do
    job = Job.new(task, queue)

    {:ok, job} =
      opts
      |> Enum.reduce(job, fn
        {:reply, true}, job ->
          %Job{job | from: {self(), make_ref()}}

        {:delay_secs, secs}, job when is_integer(secs) and secs >= 0 ->
          %Job{job | delay_secs: secs}

        {:delay_secs, thing}, job ->
          raise ArgumentError, invalid_delay_secs_error(job, thing)
      end)
      |> enqueue

    job
  end

  @doc """
  Wait for a job to complete and return result.

  Returns the result of a job, or `nil` on timeout. Raises an `ArgumentError` if
  the job was not created with `reply: true` and in the current process.

  ## Example

  Calling `yield/2` with different timeouts.

      iex> job = Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue, reply: true)
      iex> Honeydew.yield(job, 500) # Wait half a second
      nil
      # Result comes in at 1 second
      iex> Honeydew.yield(job, 1000) # Wait up to a second
      {:ok, :pong}
      iex> Honeydew.yield(job, 0)
      nil # <- because the message has already arrived and been handled

  The only time `yield/2` would ever return the result more than once is if
  the job executes more than once (as Honeydew aims for at-least-once
  execution).
  """
  @spec yield(Job.t, timeout) :: {:ok, result} | nil | no_return
  def yield(job, timeout \\ 5000)
  def yield(%Job{from: nil} = job, _), do: raise ArgumentError, reply_not_requested_error(job)
  def yield(%Job{from: {owner, _}} = job, _) when owner != self(), do: raise ArgumentError, invalid_owner_error(job)

  def yield(%Job{from: {_, ref}}, timeout) do
    receive do
      %Job{from: {_, ^ref}, result: result} ->
        result # may be {:ok, term} or {:exit, term}
    after
      timeout ->
        nil
    end
  end

  @doc """
  Suspends job processing for a queue.
  """
  @spec suspend(queue_name) :: :ok
  def suspend(queue) do
    queue
    |> get_all_members(Queues)
    |> Enum.each(&Queue.suspend/1)
  end

  @doc """
  Resumes job processing for a queue.
  """
  @spec resume(queue_name) :: :ok
  def resume(queue) do
    queue
    |> get_all_members(Queues)
    |> Enum.each(&Queue.resume/1)
  end

  @doc """
  Returns the currrent status of the queue and all attached workers.

  You can provide any of the following `opts`:

  - `timeout`: specifies the time (in miliseconds) the calling process will wait for the queue to return the status,
               note that this timeout does not cancel the status callback execution in the queue.
  """
  @type status_opt :: {:timeout, pos_integer}
  @spec status(queue_name, [status_opt]) :: map()
  def status(queue, opts \\ []) do
    queue_status =
      queue
      |> get_queue
      |> Queue.status(opts)

    busy_workers =
      queue_status
      |> Map.get(:job_monitors)
      |> Enum.map(fn monitor ->
           try do
             JobMonitor.status(monitor)
           catch
             # the monitor may have shut down
             :exit, _ -> nil
           end
         end)
      |> Enum.reject(&(!&1))
      |> Enum.into(%{})

    workers =
      queue
      |> get_all_members(Workers)
      |> Enum.map(&{&1, nil})
      |> Enum.into(%{})
      |> Map.merge(busy_workers)

    %{queue: Map.delete(queue_status, :job_monitors), workers: workers}
  end

  @doc """
  Filters the jobs currently on the queue.

  Filtration support depends on the queue implementation.

  ErlangQueue and Mnesia queues support filtering with functions.

  Ecto Poll Queues have pre-defined, named filters. At the moment, only `:abandoned` is implemented.

  Note:
  - This function returns a `List`, not a `Stream`, so calling it can be memory intensive when invoked on a large queue.
  - The filtration is done by the queue process, not the client, so a heavy filter will tie up the queue.

  ## Examples

  Filter jobs with a specific task.

      Honeydew.filter(:my_queue, &match?(%Honeydew.Job{task: {:ping, _}}, &1)) # ErlangQueue or Mnesia

      Honeydew.filter(:my_queue, %{task: {:ping, ["127.0.0.1"]}}) # Mnesia

      Honeydew.filter(:my_queue, :abandoned) # Ecto queue

  Return all jobs.

      Honeydew.filter(:my_queue, fn _ -> true end)
  """
  @spec filter(queue_name, filter) :: [Job.t]
  def filter(queue, filter) do
    {:ok, jobs} =
      queue
      |> get_queue
      |> Queue.filter(filter)

    jobs
  end

  @doc """
  Cancels a job.

  The return value depends on the status of the job.

  * `:ok` - Job had not been started and was able to be cancelled.
  * `{:error, :in_progress}` - Job was in progress and unable to be cancelled.
  * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.
  """
  @spec cancel(Job.t) :: :ok | {:error, :in_progress} | {:error, :not_found}
  def cancel(%Job{queue: queue} = job) do
    queue
    |> get_queue
    |> Queue.cancel(job)
  end

  @doc """
  Cancels the job associated with the first argument.

  For example, for the Ecto Poll Queue, the first argument is the value of an ID from your schema.

  The return value depends on the status of the job.

  * `:ok` - Job had not been started and was able to be cancelled.
  * `{:error, :in_progress}` - Job was in progress and unable to be cancelled, the Ecto Poll Queue does not support this return.
  * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.
  """
  @spec cancel(Job.private(), queue_name) :: :ok | {:error, :in_progress} | {:error, :not_found}
  def cancel(private, queue) do
    %Job{private: private, queue: queue} |> cancel
  end

  @doc """
  Moves a job to another queue.

  Raises a `RuntimeError` if `to_queue` is not available.

  This function first enqueues the job on `to_queue`, and then tries to
  cancel it on its current queue. This means there's a possiblity a job could
  be processed on both queues. This behavior is consistent with Honeydew's
  at-least-once execution goal.

  This function is most helpful on a queue where there a no workers
  (like a dead letter queue), because the job won't be processed out from under
  the queue.
  """
  @spec move(Job.t, to_queue :: queue_name) :: Job.t | no_return
  def move(%Job{} = job, to_queue) do
    {:ok, new_job} = enqueue(%Job{job | queue: to_queue})

    # Don't worry if it fails to cancel.
    cancel(job)

    new_job
  end

  @doc false
  def enqueue(%Job{queue: queue} = job) do
    queue
    |> get_queue
    |> case do
         nil -> raise RuntimeError, no_queues_running_error(job)
         queue -> queue
       end
    |> Queue.enqueue(job)
  end

  @doc false
  def invalid_owner_error(job) do
    "job #{inspect job} must be queried from the owner but was queried from #{inspect self()}"
  end

  @doc false
  def invalid_delay_secs_error(job, secs) do
    "invalid :delay_secs argument, #{inspect secs}, provided for job #{inspect job}, must be a non-negative integer"
  end

  @doc false
  def reply_not_requested_error(job) do
    "job #{inspect job} didn't request a reply when enqueued, set `:reply` to `true`, see `async/3`"
  end

  @doc false
  def no_queues_running_error(%Job{queue: {:global, _} = queue} = job) do
    "can't enqueue job because there aren't any queue processes running for the distributed queue `#{inspect queue}, are you connected to the cluster? #{inspect job} `"
  end

  @doc false
  def no_queues_running_error(%Job{queue: queue} = job) do
    "can't enqueue job #{inspect job} because there aren't any queue processes running for `#{inspect queue}`"
  end

  @deprecated "Honeydew now supervises your queue processes, please use `Honeydew.start_queue/2 instead.`"
  def queue_spec(_name, _opts) do
    raise "Honeydew now supervises your queue processes, please use `Honeydew.start_queue/2 instead.`"
  end

  @doc """
  Returns a list of queues running on this node.
  """
  @spec queues() :: [queue_name]
  defdelegate queues(), to: Queues

  @doc """
  Returns a list of queues that have workers are running on this node.
  """
  @spec workers() :: [queue_name]
  defdelegate workers(), to: Workers

  @type queue_spec_opt ::
  {:queue, mod_or_mod_args} |
  {:dispatcher, mod_or_mod_args} |
  {:failure_mode, mod_or_mod_args | nil} |
  {:success_mode, mod_or_mod_args | nil} |
  {:supervisor_opts, supervisor_opts} |
  {:suspended, boolean}

  @doc """
  Starts a queue under Honeydew's supervision tree.

  `name` is how you'll refer to the queue to add a task.

  You can provide any of the following `opts`:

  - `queue`: is the module that queue will use. Defaults to
    `Honeydew.Queue.ErlangQueue`. You may also provide args to the queue's
    `c:Honeydew.Queue.init/2` callback using the following format:
    `{module, args}`.
  - `dispatcher`: the job dispatching strategy, `{module, init_args}`.

  - `failure_mode`: the way that failed jobs should be handled. You can pass
    either a module, or `{module, args}`. The module must implement the
    `Honeydew.FailureMode` behaviour. Defaults to
    `{Honeydew.FailureMode.Abandon, []}`.

  - `success_mode`: a callback that runs when a job successfully completes. You
     can pass either a module, or `{module, args}`. The module must implement
     the `Honeydew.SuccessMode` behaviour. Defaults to `nil`.

  - `suspended`: Start queue in suspended state. Defaults to `false`.

  For example:

  - `Honeydew.start_queue("my_awesome_queue")`

  - `Honeydew.start_queue("my_awesome_queue", queue: {MyQueueModule, [ip: "localhost"]},
                                              dispatcher: {Honeydew.Dispatcher.MRU, []})`

  Note that the `failure_mode` or `success_mode` handler is run in the job's
  dedicated monitor process. This means the handlers for multiple jobs can run
  concurrently, but they can also crash that process.
  """
  @spec start_queue(queue_name, [queue_spec_opt]) :: :ok
  defdelegate start_queue(name, opts \\ []), to: Queues

  @doc """
  Stops the local instance of the provided queue name.
  """
  @spec stop_queue(queue_name) :: :ok | {:error, :not_running}
  defdelegate stop_queue(name), to: Queues

  @type worker_opt ::
    {:num, non_neg_integer} |
    {:init_retry_secs, pos_integer} |
    {:shutdown, non_neg_integer} |
    {:nodes, [node]}

  @type worker_opts :: [worker_opt]

  @doc """
  Starts workers under Honeydew's supervision tree.

  `name` is the name of the queue that the workers pull jobs from.

  `module` is the module that the workers in your queue will use. You may also
  provide `c:Honeydew.Worker.init/1` args with `{module, args}`.

  You can provide any of the following `opts`:

  - `num`: the number of workers to start. Defaults to `10`.

  - `init_retry_secs`: the amount of time, in seconds, a stateful worker waits
  before trying to re-initialize after its `c:Honeydew.Worker.init/1` function
  fails. You can also override this behavior by implementing the
  `c:Honeydew.Worker.init_failed/0` callback, see `README/workers.md`.

  - `shutdown`: if a worker is in the middle of a job, the amount of time, in
  milliseconds, to wait before brutally killing it. Defaults to `10_000`.

  - `nodes`: for :global queues, you can provide a list of nodes to stay
     connected to (your queue node and enqueuing nodes). Defaults to `[]`.

  For example:

  - `Honeydew.start_workers("my_awesome_queue", MyJobModule)`

  - `Honeydew.start_workers("my_awesome_queue", {MyJobModule, [key: "secret key"]}, num: 3)`

  - `Honeydew.start_workers({:global, "my_awesome_queue"}, MyJobModule, nodes: [:clientfacing@dax, :queue@dax])`
  """
  defdelegate start_workers(name, module_and_args, opts \\ []), to: Honeydew.Workers

  @deprecated "Honeydew now supervises your worker processes, please use `Honeydew.start_workers/3 instead.`"
  def worker_spec(_queue, _module_and_args, _opts) do
    raise "Honeydew now supervises your worker processes, please use `Honeydew.start_workers/3 instead.`"
  end

  @doc """
  Stops the local workers for the provided queue name.
  """
  @spec stop_workers(queue_name) :: :ok | {:error, :not_running}
  defdelegate stop_workers(name), to: Workers

  @doc """
  Re-initializes the given worker, this is intended to be used from
  within a worker's `c:Honeydew.Worker.failed_init/0` callback. Using it otherwise
  may cause undefined behavior, at present, don't do it.
  """
  @spec reinitialize_worker() :: :ok
  def reinitialize_worker do
    Worker.module_init(self())
  end

  @groups [Workers, Queues]

  Enum.each(@groups, fn group ->
    @doc false
    def group(queue, unquote(group)) do
      name(queue, unquote(group))
    end
  end)

  @processes [WorkerGroupSupervisor, WorkerStarter]

  Enum.each(@processes, fn process ->
    @doc false
    def process(queue, unquote(process)) do
      name(queue, unquote(process))
    end
  end)

  @doc false
  def create_groups(queue) do
    Enum.each(@groups, fn name ->
      queue |> group(name) |> :pg2.create
    end)
  end

  @doc false
  def delete_groups(queue) do
    Enum.each(@groups, fn name ->
      queue |> group(name) |> :pg2.delete
    end)
  end

  @doc false
  def get_all_members({:global, _} = queue, name) do
    queue |> group(name) |> :pg2.get_members
  end

  @doc false
  def get_all_members(queue, name) do
    get_all_local_members(queue, name)
  end

  # we need to know local members to shut down local components
  @doc false
  def get_all_local_members(queue, name) do
    queue |> group(name) |> :pg2.get_local_members
  end

  @doc false
  def get_queue(queue) do
    queue
    |> get_all_queues
    |> case do
         {:error, {:no_such_group, _queue}} -> []
         queues -> queues
       end
    |> List.first
  end

  @doc false
  def get_all_queues({:global, _name} = queue) do
    queue
    |> group(Queues)
    |> :pg2.get_members
  end

  @doc false
  def get_all_queues(queue) do
    queue
    |> group(Queues)
    |> :pg2.get_local_members
  end

  @doc false
  def table_name({:global, queue}) do
    "global_#{queue}"
  end

  @doc false
  def table_name(queue) do
    to_string(queue)
  end

  defp name({:global, queue}, component) do
    name([:global, queue], component)
  end

  defp name(queue, component) do
    [component, queue] |> List.flatten |> Enum.join(".") |> String.to_atom
  end

  @doc false
  defmacro debug(ast) do
    quote do
      fn ->
        Logger.debug unquote(ast)
      end
    end
  end

end

defmodule Honeydew do
  @moduledoc """
  A pluggable job queue + worker pool for Elixir.
  """

  alias Honeydew.Job
  alias Honeydew.JobMonitor
  alias Honeydew.Worker
  alias Honeydew.WorkerStarter
  alias Honeydew.WorkerGroupSupervisor
  alias Honeydew.Queue
  alias Honeydew.{Queues, Workers}
  require Logger

  @type mod_or_mod_args :: module | {module, args :: term}
  @type queue_name :: String.t | atom | {:global, String.t | atom}
  @type supervisor_opts :: Keyword.t
  @type async_opt :: {:reply, true} | {:delay_secs, pos_integer()}
  @type task :: {atom, [arg :: term]}
  @type filter :: (Job.t -> boolean) | atom

  @typedoc """
  Result of a `Honeydew.Job`
  """
  @type result :: term

  #
  # Parts of this module were lovingly stolen from
  # https://github.com/elixir-lang/elixir/blob/v1.3.2/lib/elixir/lib/task.ex#L320
  #

  @doc """
  Runs a task asynchronously.

  Raises a `RuntimeError` if `queue` process is not available.

  You can provide any of the following `opts`:

  - `reply`: returns the result of the job via `yield/1`, see below.
  - `delay_secs`: delays the execution of the job by the provided number of seconds.

  ## Examples

  To run a task asynchronously:

      Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue)

  To run a task asynchronously and wait for result:

      # Without pipes
      job = Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue, reply: true)
      Honeydew.yield(job)

      # With pipes
      :pong =
        {:ping, ["127.0.0.1"]}
        |> Honeydew.async(:my_queue, reply: true)
        |> Honeydew.yield()

  To run a task an hour later:

      Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue, delay_secs: 60*60)
  """
  @spec async(task, queue_name, [async_opt]) :: Job.t | no_return
  def async(task, queue, opts \\ []) do
    job = Job.new(task, queue)

    {:ok, job} =
      opts
      |> Enum.reduce(job, fn
        {:reply, true}, job ->
          %Job{job | from: {self(), make_ref()}}

        {:delay_secs, secs}, job when is_integer(secs) and secs >= 0 ->
          %Job{job | delay_secs: secs}

        {:delay_secs, thing}, job ->
          raise ArgumentError, invalid_delay_secs_error(job, thing)
      end)
      |> enqueue

    job
  end

  @doc """
  Wait for a job to complete and return result.

  Returns the result of a job, or `nil` on timeout. Raises an `ArgumentError` if
  the job was not created with `reply: true` and in the current process.

  ## Example

  Calling `yield/2` with different timeouts.

      iex> job = Honeydew.async({:ping, ["127.0.0.1"]}, :my_queue, reply: true)
      iex> Honeydew.yield(job, 500) # Wait half a second
      nil
      # Result comes in at 1 second
      iex> Honeydew.yield(job, 1000) # Wait up to a second
      {:ok, :pong}
      iex> Honeydew.yield(job, 0)
      nil # <- because the message has already arrived and been handled

  The only time `yield/2` would ever return the result more than once is if
  the job executes more than once (as Honeydew aims for at-least-once
  execution).
  """
  @spec yield(Job.t, timeout) :: {:ok, result} | nil | no_return
  def yield(job, timeout \\ 5000)
  def yield(%Job{from: nil} = job, _), do: raise ArgumentError, reply_not_requested_error(job)
  def yield(%Job{from: {owner, _}} = job, _) when owner != self(), do: raise ArgumentError, invalid_owner_error(job)

  def yield(%Job{from: {_, ref}}, timeout) do
    receive do
      %Job{from: {_, ^ref}, result: result} ->
        result # may be {:ok, term} or {:exit, term}
    after
      timeout ->
        nil
    end
  end

  @doc """
  Suspends job processing for a queue.
  """
  @spec suspend(queue_name) :: :ok
  def suspend(queue) do
    queue
    |> get_all_members(Queues)
    |> Enum.each(&Queue.suspend/1)
  end

  @doc """
  Resumes job processing for a queue.
  """
  @spec resume(queue_name) :: :ok
  def resume(queue) do
    queue
    |> get_all_members(Queues)
    |> Enum.each(&Queue.resume/1)
  end

  @doc """
  Returns the currrent status of the queue and all attached workers.

  You can provide any of the following `opts`:

  - `timeout`: specifies the time (in miliseconds) the calling process will wait for the queue to return the status,
               note that this timeout does not cancel the status callback execution in the queue.
  """
  @type status_opt :: {:timeout, pos_integer}
  @spec status(queue_name, [status_opt]) :: map()
  def status(queue, opts \\ []) do
    queue_status =
      queue
      |> get_queue
      |> Queue.status(opts)

    busy_workers =
      queue_status
      |> Map.get(:job_monitors)
      |> Enum.map(fn monitor ->
           try do
             JobMonitor.status(monitor)
           catch
             # the monitor may have shut down
             :exit, _ -> nil
           end
         end)
      |> Enum.reject(&(!&1))
      |> Enum.into(%{})

    workers =
      queue
      |> get_all_members(Workers)
      |> Enum.map(&{&1, nil})
      |> Enum.into(%{})
      |> Map.merge(busy_workers)

    %{queue: Map.delete(queue_status, :job_monitors), workers: workers}
  end

  @doc """
  Filters the jobs currently on the queue.

  Filtration support depends on the queue implementation.

  ErlangQueue and Mnesia queues support filtering with functions.

  Ecto Poll Queues have pre-defined, named filters. At the moment, only `:abandoned` is implemented.

  Note:
  - This function returns a `List`, not a `Stream`, so calling it can be memory intensive when invoked on a large queue.
  - The filtration is done by the queue process, not the client, so a heavy filter will tie up the queue.

  ## Examples

  Filter jobs with a specific task.

      Honeydew.filter(:my_queue, &match?(%Honeydew.Job{task: {:ping, _}}, &1)) # ErlangQueue or Mnesia

      Honeydew.filter(:my_queue, %{task: {:ping, ["127.0.0.1"]}}) # Mnesia

      Honeydew.filter(:my_queue, :abandoned) # Ecto queue

  Return all jobs.

      Honeydew.filter(:my_queue, fn _ -> true end)
  """
  @spec filter(queue_name, filter) :: [Job.t]
  def filter(queue, filter) do
    {:ok, jobs} =
      queue
      |> get_queue
      |> Queue.filter(filter)

    jobs
  end

  @doc """
  Cancels a job.

  The return value depends on the status of the job.

  * `:ok` - Job had not been started and was able to be cancelled.
  * `{:error, :in_progress}` - Job was in progress and unable to be cancelled.
  * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.
  """
  @spec cancel(Job.t) :: :ok | {:error, :in_progress} | {:error, :not_found}
  def cancel(%Job{queue: queue} = job) do
    queue
    |> get_queue
    |> Queue.cancel(job)
  end

  @doc """
  Cancels the job associated with the first argument.

  For example, for the Ecto Poll Queue, the first argument is the value of an ID from your schema.

  The return value depends on the status of the job.

  * `:ok` - Job had not been started and was able to be cancelled.
  * `{:error, :in_progress}` - Job was in progress and unable to be cancelled, the Ecto Poll Queue does not support this return.
  * `{:error, :not_found}` - Job was not found on the queue (or already processed) and was unable to be cancelled.
  """
  @spec cancel(Job.private(), queue_name) :: :ok | {:error, :in_progress} | {:error, :not_found}
  def cancel(private, queue) do
    %Job{private: private, queue: queue} |> cancel
  end

  @doc """
  Moves a job to another queue.

  Raises a `RuntimeError` if `to_queue` is not available.

  This function first enqueues the job on `to_queue`, and then tries to
  cancel it on its current queue. This means there's a possiblity a job could
  be processed on both queues. This behavior is consistent with Honeydew's
  at-least-once execution goal.

  This function is most helpful on a queue where there a no workers
  (like a dead letter queue), because the job won't be processed out from under
  the queue.
  """
  @spec move(Job.t, to_queue :: queue_name) :: Job.t | no_return
  def move(%Job{} = job, to_queue) do
    {:ok, new_job} = enqueue(%Job{job | queue: to_queue})

    # Don't worry if it fails to cancel.
    cancel(job)

    new_job
  end

  @doc false
  def enqueue(%Job{queue: queue} = job) do
    queue
    |> get_queue
    |> case do
         nil -> raise RuntimeError, no_queues_running_error(job)
         queue -> queue
       end
    |> Queue.enqueue(job)
  end

  @doc false
  def invalid_owner_error(job) do
    "job #{inspect job} must be queried from the owner but was queried from #{inspect self()}"
  end

  @doc false
  def invalid_delay_secs_error(job, secs) do
    "invalid :delay_secs argument, #{inspect secs}, provided for job #{inspect job}, must be a non-negative integer"
  end

  @doc false
  def reply_not_requested_error(job) do
    "job #{inspect job} didn't request a reply when enqueued, set `:reply` to `true`, see `async/3`"
  end

  @doc false
  def no_queues_running_error(%Job{queue: {:global, _} = queue} = job) do
    "can't enqueue job because there aren't any queue processes running for the distributed queue `#{inspect queue}, are you connected to the cluster? #{inspect job} `"
  end

  @doc false
  def no_queues_running_error(%Job{queue: queue} = job) do
    "can't enqueue job #{inspect job} because there aren't any queue processes running for `#{inspect queue}`"
  end

  @deprecated "Honeydew now supervises your queue processes, please use `Honeydew.start_queue/2 instead.`"
  def queue_spec(_name, _opts) do
    raise "Honeydew now supervises your queue processes, please use `Honeydew.start_queue/2 instead.`"
  end

  @doc """
  Returns a list of queues running on this node.
  """
  @spec queues() :: [queue_name]
  defdelegate queues(), to: Queues

  @doc """
  Returns a list of queues that have workers are running on this node.
  """
  @spec workers() :: [queue_name]
  defdelegate workers(), to: Workers

  @type queue_spec_opt ::
  {:queue, mod_or_mod_args} |
  {:dispatcher, mod_or_mod_args} |
  {:failure_mode, mod_or_mod_args | nil} |
  {:success_mode, mod_or_mod_args | nil} |
  {:supervisor_opts, supervisor_opts} |
  {:suspended, boolean}

  @doc """
  Starts a queue under Honeydew's supervision tree.

  `name` is how you'll refer to the queue to add a task.

  You can provide any of the following `opts`:

  - `queue`: is the module that queue will use. Defaults to
    `Honeydew.Queue.ErlangQueue`. You may also provide args to the queue's
    `c:Honeydew.Queue.init/2` callback using the following format:
    `{module, args}`.
  - `dispatcher`: the job dispatching strategy, `{module, init_args}`.

  - `failure_mode`: the way that failed jobs should be handled. You can pass
    either a module, or `{module, args}`. The module must implement the
    `Honeydew.FailureMode` behaviour. Defaults to
    `{Honeydew.FailureMode.Abandon, []}`.

  - `success_mode`: a callback that runs when a job successfully completes. You
     can pass either a module, or `{module, args}`. The module must implement
     the `Honeydew.SuccessMode` behaviour. Defaults to `nil`.

  - `suspended`: Start queue in suspended state. Defaults to `false`.

  For example:

  - `Honeydew.start_queue("my_awesome_queue")`

  - `Honeydew.start_queue("my_awesome_queue", queue: {MyQueueModule, [ip: "localhost"]},
                                              dispatcher: {Honeydew.Dispatcher.MRU, []})`
  """
  @spec start_queue(queue_name, [queue_spec_opt]) :: :ok
  defdelegate start_queue(name, opts \\ []), to: Queues

  @doc """
  Stops the local instance of the provided queue name.
  """
  @spec stop_queue(queue_name) :: :ok | {:error, :not_running}
  defdelegate stop_queue(name), to: Queues

  @type worker_opt ::
    {:num, non_neg_integer} |
    {:init_retry_secs, pos_integer} |
    {:shutdown, non_neg_integer} |
    {:nodes, [node]}

  @type worker_opts :: [worker_opt]

  @doc """
  Starts workers under Honeydew's supervision tree.

  `name` is the name of the queue that the workers pull jobs from.

  `module` is the module that the workers in your queue will use. You may also
  provide `c:Honeydew.Worker.init/1` args with `{module, args}`.

  You can provide any of the following `opts`:

  - `num`: the number of workers to start. Defaults to `10`.

  - `init_retry_secs`: the amount of time, in seconds, a stateful worker waits
  before trying to re-initialize after its `c:Honeydew.Worker.init/1` function
  fails. You can also override this behavior by implementing the
  `c:Honeydew.Worker.init_failed/0` callback, see `README/workers.md`.

  - `shutdown`: if a worker is in the middle of a job, the amount of time, in
  milliseconds, to wait before brutally killing it. Defaults to `10_000`.

  - `nodes`: for :global queues, you can provide a list of nodes to stay
     connected to (your queue node and enqueuing nodes). Defaults to `[]`.

  For example:

  - `Honeydew.start_workers("my_awesome_queue", MyJobModule)`

  - `Honeydew.start_workers("my_awesome_queue", {MyJobModule, [key: "secret key"]}, num: 3)`

  - `Honeydew.start_workers({:global, "my_awesome_queue"}, MyJobModule, nodes: [:clientfacing@dax, :queue@dax])`
  """
  defdelegate start_workers(name, module_and_args, opts \\ []), to: Honeydew.Workers

  @deprecated "Honeydew now supervises your worker processes, please use `Honeydew.start_workers/3 instead.`"
  def worker_spec(_queue, _module_and_args, _opts) do
    raise "Honeydew now supervises your worker processes, please use `Honeydew.start_workers/3 instead.`"
  end

  @doc """
  Stops the local workers for the provided queue name.
  """
  @spec stop_workers(queue_name) :: :ok | {:error, :not_running}
  defdelegate stop_workers(name), to: Workers

  @doc """
  Re-initializes the given worker, this is intended to be used from
  within a worker's `c:Honeydew.Worker.failed_init/0` callback. Using it otherwise
  may cause undefined behavior, at present, don't do it.
  """
  @spec reinitialize_worker() :: :ok
  def reinitialize_worker do
    Worker.module_init(self())
  end

  @groups [Workers, Queues]

  Enum.each(@groups, fn group ->
    @doc false
    def group(queue, unquote(group)) do
      name(queue, unquote(group))
    end
  end)

  @processes [WorkerGroupSupervisor, WorkerStarter]

  Enum.each(@processes, fn process ->
    @doc false
    def process(queue, unquote(process)) do
      name(queue, unquote(process))
    end
  end)

  @doc false
  def create_groups(queue) do
    Enum.each(@groups, fn name ->
      queue |> group(name) |> :pg2.create
    end)
  end

  @doc false
  def delete_groups(queue) do
    Enum.each(@groups, fn name ->
      queue |> group(name) |> :pg2.delete
    end)
  end

  @doc false
  def get_all_members({:global, _} = queue, name) do
    queue |> group(name) |> :pg2.get_members
  end

  @doc false
  def get_all_members(queue, name) do
    get_all_local_members(queue, name)
  end

  # we need to know local members to shut down local components
  @doc false
  def get_all_local_members(queue, name) do
    queue |> group(name) |> :pg2.get_local_members
  end

  @doc false
  def get_queue(queue) do
    queue
    |> get_all_queues
    |> case do
         {:error, {:no_such_group, _queue}} -> []
         queues -> queues
       end
    |> List.first
  end

  @doc false
  def get_all_queues({:global, _name} = queue) do
    queue
    |> group(Queues)
    |> :pg2.get_members
  end

  @doc false
  def get_all_queues(queue) do
    queue
    |> group(Queues)
    |> :pg2.get_local_members
  end

  @doc false
  def table_name({:global, queue}) do
    "global_#{queue}"
  end

  @doc false
  def table_name(queue) do
    to_string(queue)
  end

  defp name({:global, queue}, component) do
    name([:global, queue], component)
  end

  defp name(queue, component) do
    [component, queue] |> List.flatten |> Enum.join(".") |> String.to_atom
  end

  @doc false
  defmacro debug(ast) do
    quote do
      fn ->
        Logger.debug unquote(ast)
      end
    end
  end

end


Reformat

Reformat

defmodule Xema.Ref do
  @moduledoc """
  This module contains a struct and function to represent and handle references.
  """

  import Xema.Utils, only: [get_value: 2, update_nil: 2]

  alias Xema.Ref
  alias Xema.Schema
  alias Xema.SchemaError

  require Logger

  @type t :: %Xema.Ref{
          path: String.t() | nil,
          pointer: String.t(),
          remote: boolean(),
          url: String.t() | nil
        }

  defstruct pointer: nil,
            path: nil,
            remote: false,
            url: nil

  @doc """
  Creates a new reference from the given `pointer`.

  ## Examples

      iex> Xema.Ref.new("http://foo.com/bar/baz.exon#/definitions/abc")
      %Xema.Ref{
        path: "/bar/baz.exon",
        pointer: "/definitions/abc",
        remote: true,
        url: "http://foo.com:80"
      }

  """
  @spec new(String.t()) :: Ref.t()
  def new(pointer) when is_binary(pointer) do
    uri = URI.parse(pointer)
    path = uri |> Map.get(:path)
    pointer = uri |> Map.get(:fragment)
    remote = !is_nil(path) && Regex.match?(~r/(?:\..+#)|(?:\..+$)/, path)

    url =
      unless is_nil(uri.scheme) do
        port =
          if is_nil(uri.port),
            do: "",
            else: ":#{Integer.to_string(uri.port)}"

        "#{uri.scheme}://#{uri.host}#{port}"
      end

    %Ref{
      pointer: pointer,
      path: path,
      remote: remote,
      url: url
    }
  end

  @doc """
  Validates the given value with the referenced schema.
  """
  @spec validate(Ref.t(), any, keyword) :: :ok | {:error, map}
  def validate(ref, value, opts) do
    case get(ref, opts) do
      {:ok, %Schema{} = schema, opts} ->
        Xema.validate(schema, value, opts)

      {:ok, %Ref{} = ref, opts} ->
        validate(ref, value, opts)

      {:error, :not_found} ->
        raise SchemaError,
          message: "Reference '#{Ref.get_pointer(ref)}' not found."
    end
  end

  defp get(%Ref{remote: false, path: nil, pointer: pointer}, opts) do
    with {:ok, schema} <- do_get(pointer, opts[:root]), do: {:ok, schema, opts}
  end

  defp get(%Ref{remote: false, path: path, pointer: nil}, opts) do
    id =
      opts[:id]
      |> URI.parse()
      |> Map.put(:path, Path.join("/", path))
      |> URI.to_string()

    with {:ok, ref} <- get_ref(opts[:root], id), do: {:ok, ref, opts}
  end

  defp get(%Ref{remote: true, url: nil, path: path, pointer: pointer}, opts) do
    uri = URI.parse(opts[:id])

    uri =
      case is_nil(uri.path) || !String.ends_with?(uri.path, "/") do
        true -> Map.put(uri, :path, Path.join("/", path))
        false -> Map.put(uri, :path, Path.join(uri.path, path))
      end

    with {:ok, xema} <- get_xema(opts[:root], URI.to_string(uri)),
         {:ok, schema} <- do_get(pointer, xema),
         do: {:ok, schema, root: xema}
  end

  defp get(%Ref{remote: true, url: url, path: path, pointer: pointer}, opts) do
    uri = Path.join(url, path)

    # xema = Map.get(opts[:root].refs, uri)

    with {:ok, xema} <- get_xema(opts[:root], uri),
         {:ok, schema} <- do_get(pointer, xema),
         do: {:ok, schema, root: xema}
  end

  defp get(_ref, _opts), do: {:error, :not_found}

  defp do_get(_, nil), do: {:error, :not_found}

  defp do_get(pointer, %{__struct__: _, content: content}) do
    case pointer in [nil, "", "#"] do
      true -> {:ok, content}
      false -> do_get(pointer, content)
    end
  end

  defp do_get(pointer, schema)
       when is_binary(pointer),
       do:
         pointer
         |> String.trim("/")
         |> String.split("/")
         |> do_get(schema)

  defp do_get([], schema), do: {:ok, schema}

  defp do_get([step | steps], schema) when is_map(schema) do
    case get_value(schema, decode(step)) do
      {:ok, value} ->
        do_get(steps, value)

      {:error, _} ->
        {:error, :not_found}
    end
  end

  defp do_get([step | steps], schema) when is_list(schema) do
    with {:ok, index} <- to_integer(step) do
      case Enum.at(schema, index) do
        nil -> {:error, :not_found}
        value -> do_get(steps, value)
      end
    end
  end

  defp get_ref(%{ids: refs}, id) do
    case Map.get(refs, id) do
      nil -> {:error, :not_found}
      ref -> {:ok, ref}
    end
  end

  defp get_ref(_, _), do: {:error, :not_found}

  defp get_xema(%{refs: xemas}, pointer) do
    case Map.get(xemas, pointer) do
      nil ->
        {:error, :not_found}

      xema ->
        {:ok, xema}
    end
  end

  defp get_xema(_, _), do: {:error, :not_found}

  defp decode(str) do
    str
    |> String.replace("~0", "~")
    |> String.replace("~1", "/")
    |> URI.decode()
  rescue
    _ -> str
  end

  defp to_integer(str) do
    case Regex.run(~r/\d+/, str) do
      nil -> {:error, :not_found}
      [int] -> {:ok, String.to_integer(int)}
    end
  end

  @doc """
  Returns the `pointer` of the given reference.
  """
  @spec get_pointer(Ref.t()) :: String.t()
  def get_pointer(ref) do
    ref.url
    |> update_nil("")
    |> URI.parse()
    |> Map.put(:path, ref.path)
    |> Map.put(:fragment, ref.pointer)
    |> URI.to_string()
  end

  @doc """
  Returns the binary representation of a reference.

  ## Examples

      iex> "http://foo.com/bar/baz.exon#/definitions/abc"
      ...> |> Xema.Ref.new()
      ...> |> Xema.Ref.to_string()
      "{:ref, \\"http://foo.com/bar/baz.exon#/definitions/abc\\"}"

  """
  @spec to_string(Ref.t()) :: String.t()
  def to_string(ref), do: "{:ref, #{inspect(get_pointer(ref))}}"
end

defimpl String.Chars, for: Xema.Ref do
  @spec to_string(Xema.Ref.t()) :: String.t()
  def to_string(ref), do: Xema.Ref.to_string(ref)
end

defmodule Xema.Ref do
  @moduledoc """
  This module contains a struct and function to represent and handle references.
  """

  import Xema.Utils, only: [get_value: 2, update_nil: 2]

  alias Xema.Ref
  alias Xema.Schema
  alias Xema.SchemaError

  require Logger

  @type t :: %Xema.Ref{
          path: String.t() | nil,
          pointer: String.t(),
          remote: boolean(),
          url: String.t() | nil
        }

  defstruct pointer: nil,
            path: nil,
            remote: false,
            url: nil

  @doc """
  Creates a new reference from the given `pointer`.

  ## Examples

      iex> Xema.Ref.new("http://foo.com/bar/baz.exon#/definitions/abc")
      %Xema.Ref{
        path: "/bar/baz.exon",
        pointer: "/definitions/abc",
        remote: true,
        url: "http://foo.com:80"
      }

  """
  @spec new(String.t()) :: Ref.t()
  def new(pointer) when is_binary(pointer) do
    uri = URI.parse(pointer)
    path = uri |> Map.get(:path)
    pointer = uri |> Map.get(:fragment)
    remote = !is_nil(path) && Regex.match?(~r/(?:\..+#)|(?:\..+$)/, path)

    url =
      unless is_nil(uri.scheme) do
        port =
          if is_nil(uri.port),
            do: "",
            else: ":#{Integer.to_string(uri.port)}"

        "#{uri.scheme}://#{uri.host}#{port}"
      end

    %Ref{
      pointer: pointer,
      path: path,
      remote: remote,
      url: url
    }
  end

  @doc """
  Validates the given value with the referenced schema.
  """
  @spec validate(Ref.t(), any, keyword) :: :ok | {:error, map}
  def validate(ref, value, opts) do
    case get(ref, opts) do
      {:ok, %Schema{} = schema, opts} ->
        Xema.validate(schema, value, opts)

      {:ok, %Ref{} = ref, opts} ->
        validate(ref, value, opts)

      {:error, :not_found} ->
        raise SchemaError,
          message: "Reference '#{Ref.get_pointer(ref)}' not found."
    end
  end

  defp get(%Ref{remote: false, path: nil, pointer: pointer}, opts) do
    with {:ok, schema} <- do_get(pointer, opts[:root]), do: {:ok, schema, opts}
  end

  defp get(%Ref{remote: false, path: path, pointer: nil}, opts) do
    id =
      opts[:id]
      |> URI.parse()
      |> Map.put(:path, Path.join("/", path))
      |> URI.to_string()

    with {:ok, ref} <- get_ref(opts[:root], id), do: {:ok, ref, opts}
  end

  defp get(%Ref{remote: true, url: nil, path: path, pointer: pointer}, opts) do
    uri = URI.parse(opts[:id])

    uri =
      case is_nil(uri.path) || !String.ends_with?(uri.path, "/") do
        true -> Map.put(uri, :path, Path.join("/", path))
        false -> Map.put(uri, :path, Path.join(uri.path, path))
      end

    # xema = Map.get(opts[:root].refs, URI.to_string(uri))

    with {:ok, xema} <- get_xema(opts[:root], URI.to_string(uri)),
         {:ok, schema} <- do_get(pointer, xema),
         do: {:ok, schema, root: xema}
  end

  defp get(%Ref{remote: true, url: url, path: path, pointer: pointer}, opts) do
    uri = Path.join(url, path)

    # xema = Map.get(opts[:root].refs, uri)

    with {:ok, xema} <- get_xema(opts[:root], uri),
         {:ok, schema} <- do_get(pointer, xema),
         do: {:ok, schema, root: xema}
  end

  defp get(_ref, _opts), do: {:error, :not_found}

  defp do_get(_, nil), do: {:error, :not_found}

  defp do_get(pointer, %{__struct__: _, content: content}) do
    case pointer in [nil, "", "#"] do
      true -> {:ok, content}
      false -> do_get(pointer, content)
    end
  end

  defp do_get(pointer, schema)
       when is_binary(pointer),
       do:
         pointer
         |> String.trim("/")
         |> String.split("/")
         |> do_get(schema)

  defp do_get([], schema), do: {:ok, schema}

  defp do_get([step | steps], schema) when is_map(schema) do
    case get_value(schema, decode(step)) do
      {:ok, value} ->
        do_get(steps, value)

      {:error, _} ->
        {:error, :not_found}
    end
  end

  defp do_get([step | steps], schema) when is_list(schema) do
    with {:ok, index} <- to_integer(step) do
      case Enum.at(schema, index) do
        nil -> {:error, :not_found}
        value -> do_get(steps, value)
      end
    end
  end

  defp get_ref(%{ids: refs}, id) do
    case Map.get(refs, id) do
      nil -> {:error, :not_found}
      ref -> {:ok, ref}
    end
  end

  defp get_ref(_, _), do: {:error, :not_found}

  defp get_xema(%{refs: xemas}, pointer) do
    case Map.get(xemas, pointer) do
      nil -> {:error, :not_found}
      xema -> {:ok, xema}
    end
  end

  defp get_xema(_, _), do: {:error, :not_found}

  defp decode(str) do
    str
    |> String.replace("~0", "~")
    |> String.replace("~1", "/")
    |> URI.decode()
  rescue
    _ -> str
  end

  defp to_integer(str) do
    case Regex.run(~r/\d+/, str) do
      nil -> {:error, :not_found}
      [int] -> {:ok, String.to_integer(int)}
    end
  end

  @doc """
  Returns the `pointer` of the given reference.
  """
  @spec get_pointer(Ref.t()) :: String.t()
  def get_pointer(ref) do
    ref.url
    |> update_nil("")
    |> URI.parse()
    |> Map.put(:path, ref.path)
    |> Map.put(:fragment, ref.pointer)
    |> URI.to_string()
  end

  @doc """
  Returns the binary representation of a reference.

  ## Examples

      iex> "http://foo.com/bar/baz.exon#/definitions/abc"
      ...> |> Xema.Ref.new()
      ...> |> Xema.Ref.to_string()
      "{:ref, \\"http://foo.com/bar/baz.exon#/definitions/abc\\"}"

  """
  @spec to_string(Ref.t()) :: String.t()
  def to_string(ref), do: "{:ref, #{inspect(get_pointer(ref))}}"
end

defimpl String.Chars, for: Xema.Ref do
  @spec to_string(Xema.Ref.t()) :: String.t()
  def to_string(ref), do: Xema.Ref.to_string(ref)
end


added number to number+ordinal suffix function

defmodule Number.Human do
  @moduledoc """
  Provides functions for converting numbers into more human readable strings.
  """

  import Number.Delimit, only: [number_to_delimited: 2]
  import Decimal, only: [cmp: 2]

  @doc """
  Formats and labels a number with the appropriate English word.

  ## Examples

      iex> Number.Human.number_to_human(123)
      "123.00"

      iex> Number.Human.number_to_human(1234)
      "1.23 Thousand"

      iex> Number.Human.number_to_human(999001)
      "999.00 Thousand"

      iex> Number.Human.number_to_human(1234567)
      "1.23 Million"

      iex> Number.Human.number_to_human(1234567890)
      "1.23 Billion"

      iex> Number.Human.number_to_human(1234567890123)
      "1.23 Trillion"

      iex> Number.Human.number_to_human(1234567890123456)
      "1.23 Quadrillion"

      iex> Number.Human.number_to_human(1234567890123456789)
      "1,234.57 Quadrillion"

      iex> Number.Human.number_to_human(Decimal.new("5000.0"))
      "5.00 Thousand"
  """
  def number_to_human(number, options \\ [])

  def number_to_human(number, options) when not is_map(number) do
    if Number.Conversion.impl_for(number) do
      number
      |> Number.Conversion.to_decimal
      |> number_to_human(options)
    else
      raise ArgumentError, """
      number must be a float or integer, or implement `Number.Conversion` protocol,
      was #{inspect number}"
      """
    end
  end

  def number_to_human(number, options) do
    cond do
      cmp(number, ~d(999)) == :gt && cmp(number, ~d(1_000_000)) == :lt ->
        delimit(number, ~d(1_000), "Thousand", options)
      cmp(number, ~d(1_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000)) == :lt ->
        delimit(number, ~d(1_000_000), "Million", options)
      cmp(number, ~d(1_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000)) == :lt ->
        delimit(number, ~d(1_000_000_000), "Billion", options)
      cmp(number, ~d(1_000_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000_000)) == :lt ->
        delimit(number, ~d(1_000_000_000_000), "Trillion", options)
      cmp(number, ~d(1_000_000_000_000_000)) in [:gt, :eq] ->
        delimit(number, ~d(1_000_000_000_000_000), "Quadrillion", options)
      true ->
        number_to_delimited(number, options)
    end
  end

  @doc """
  Adds ordinal suffix (st, nd, rd or th) for the number
  """
  def number_to_ordinal(number) when is_integer(number) do
    sfx = ~w(th st nd rd th th th th th th)

    if (rem(number, 100) >= 11) && (rem(number, 100) <= 13) do
      "#{number}th"
    else
      "#{number}#{sfx |> Enum.at(rem(number, 10))}"
    end
  end

  defp sigil_d(number, _modifiers) do
    number
    |> String.replace("_", "")
    |> String.to_integer
    |> Decimal.new
  end

  defp delimit(number, divisor, label, options) do
    number =
      number
      |> Decimal.div(divisor)
      |> number_to_delimited(options)

    number <> " " <> label
  end
end

defmodule Number.Human do
  @moduledoc """
  Provides functions for converting numbers into more human readable strings.
  """

  import Number.Delimit, only: [number_to_delimited: 2]
  import Decimal, only: [cmp: 2]

  @doc """
  Formats and labels a number with the appropriate English word.

  ## Examples

      iex> Number.Human.number_to_human(123)
      "123.00"

      iex> Number.Human.number_to_human(1234)
      "1.23 Thousand"

      iex> Number.Human.number_to_human(999001)
      "999.00 Thousand"

      iex> Number.Human.number_to_human(1234567)
      "1.23 Million"

      iex> Number.Human.number_to_human(1234567890)
      "1.23 Billion"

      iex> Number.Human.number_to_human(1234567890123)
      "1.23 Trillion"

      iex> Number.Human.number_to_human(1234567890123456)
      "1.23 Quadrillion"

      iex> Number.Human.number_to_human(1234567890123456789)
      "1,234.57 Quadrillion"

      iex> Number.Human.number_to_human(Decimal.new("5000.0"))
      "5.00 Thousand"
  """
  def number_to_human(number, options \\ [])

  def number_to_human(number, options) when not is_map(number) do
    if Number.Conversion.impl_for(number) do
      number
      |> Number.Conversion.to_decimal
      |> number_to_human(options)
    else
      raise ArgumentError, """
      number must be a float or integer, or implement `Number.Conversion` protocol,
      was #{inspect number}"
      """
    end
  end

  def number_to_human(number, options) do
    cond do
      cmp(number, ~d(999)) == :gt && cmp(number, ~d(1_000_000)) == :lt ->
        delimit(number, ~d(1_000), "Thousand", options)
      cmp(number, ~d(1_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000)) == :lt ->
        delimit(number, ~d(1_000_000), "Million", options)
      cmp(number, ~d(1_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000)) == :lt ->
        delimit(number, ~d(1_000_000_000), "Billion", options)
      cmp(number, ~d(1_000_000_000_000)) in [:gt, :eq] and cmp(number, ~d(1_000_000_000_000_000)) == :lt ->
        delimit(number, ~d(1_000_000_000_000), "Trillion", options)
      cmp(number, ~d(1_000_000_000_000_000)) in [:gt, :eq] ->
        delimit(number, ~d(1_000_000_000_000_000), "Quadrillion", options)
      true ->
        number_to_delimited(number, options)
    end
  end

  defp sigil_d(number, _modifiers) do
    number
    |> String.replace("_", "")
    |> String.to_integer
    |> Decimal.new
  end

  defp delimit(number, divisor, label, options) do
    number =
      number
      |> Decimal.div(divisor)
      |> number_to_delimited(options)

    number <> " " <> label
  end
end


remove

remove

defmodule Panglao.Cron.Caller do

  @hoston Application.get_env(:panglao, __MODULE__)

  defp call(fun) do
    with {:ok, [{_, _, _}| _] = ifcnf} <- :inet.getif() do
      call fun, ifcnf
    else error ->
      error
    end
  end
  defp call(_, []) do
    {:error, "N/A"}
  end
  defp call(fun, [{@hoston, _, _} | _]) do
    fun.()
  end
  defp call(fun, [_ | tail]) do
    call fun, tail
  end

  def remove_perform do
    call fn ->
      Panglao.Tasks.Remove.perform
    end
  end

  def remove_perform_disksize do
    call fn ->
      Panglao.Tasks.Remove.perform :disksize
    end
  end

  def cleanup_unses_files do
    call fn ->
      Panglao.Tasks.Cleanup.unses_files
    end
  end

  def touch_perform do
    call fn ->
      Panglao.Tasks.Touch.perform
    end
  end

end