summaryrefslogblamecommitdiff
path: root/lib/lsg_irc/quatre_cent_vingt_plugin.ex
blob: 7c3067cdb84816b7bda9d35609657f378c790eb3 (plain) (tree)


























                                                                                                                                                                        
                           












































































                                                                                                                            
defmodule LSG.IRC.QuatreCentVingtPlugin do
  require Logger

  @moduledoc """
  # 420

  * **!420**: recorde un nouveau 420.
  * **!420 pseudo**: stats du pseudo.
  """

  @achievements %{
    1    => ["[le premier… il faut bien commencer un jour]"],
    10   => ["T'en es seulement à 10 ? ╭∩╮(Ο_Ο)╭∩╮"],
    42   => ["Bravo, et est-ce que autant de pétards t'on aidés à trouver la Réponse ? ٩(- ̮̮̃-̃)۶ [42]"],
    100  => ["°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸ 100 °º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸"],
    115  => [" ۜ\(סּںסּَ` )/ۜ 115!!"]
  }

  @emojis [
    "\\o/",
    "~o~",
    "~~o∞~~",
    "*\\o/*",
    "**\\o/**",
    "*ô*",
  ]

  @coeffs Range.new(1, 100)

  def irc_doc, do: @moduledoc

  def start_link, do: GenServer.start_link(__MODULE__, [])

  def init(_) do
    for coeff <- @coeffs do
      {:ok, _} = Registry.register(IRC.PubSub, "trigger:#{420*coeff}", [])
    end
    dets_filename = (LSG.data_path() <> "/" <> "420.dets") |> String.to_charlist
    {:ok, dets} = :dets.open_file(dets_filename, [{:type,:bag}])
    {:ok, dets}
  end

  for coeff <- @coeffs do
    qvc = to_string(420 * coeff)
    def handle_info({:irc, :trigger, unquote(qvc), m = %IRC.Message{trigger: %IRC.Trigger{args: [], type: :bang}}}, dets) do
      {count, last} = get_statistics_for_nick(dets, m.sender.nick)
      count = count + unquote(coeff)
      text = achievement_text(count)
      now = DateTime.to_unix(DateTime.utc_now())-1 # this is ugly
      for i <- Range.new(1, unquote(coeff)) do
        :ok = :dets.insert(dets, {String.downcase(m.sender.nick), now+i})
      end
      last_s = if last do
        last_s = format_relative_timestamp(last)
        " (le dernier était #{last_s})"
      else
        ""
      end
      m.replyfun.("#{m.sender.nick} 420 +#{unquote(coeff)} #{text}#{last_s}")
      {:noreply, dets}
    end
  end

  def handle_info({:irc, :trigger, "420", m = %IRC.Message{trigger: %IRC.Trigger{args: [nick], type: :bang}}}, dets) do
    text = case get_statistics_for_nick(dets, nick) do
      {0, _} -> "#{nick} n'a jamais !420 ... honte à lui."
      {count, last} ->
        last_s = format_relative_timestamp(last)
        "#{nick} 420: total #{count}, le dernier #{last_s}"
    end
    m.replyfun.(text)
    {:noreply, dets}
  end

  defp format_relative_timestamp(timestamp) do
    alias Timex.Format.DateTime.Formatters
    alias Timex.Timezone
    date = timestamp
    |> DateTime.from_unix!
    |> Timezone.convert("Europe/Paris")

    {:ok, relative} = Formatters.Relative.relative_to(date, Timex.now("Europe/Paris"), "{relative}", "fr")
    {:ok, detail} = Formatters.Default.lformat(date, " ({h24}:{m})", "fr")

    relative <> detail
  end

  defp get_statistics_for_nick(dets, nick) do
    qvc = :dets.lookup(dets, String.downcase(nick)) |> Enum.sort
    count = Enum.reduce(qvc, 0, fn(_, acc) -> acc + 1 end)
    {_, last} = List.last(qvc) || {nil, nil}
    {count, last}
  end

  @achievements_keys Map.keys(@achievements)
  defp achievement_text(count) when count in @achievements_keys do
    Enum.random(Map.get(@achievements, count))
  end

  defp achievement_text(count) do
    emoji = Enum.random(@emojis)
    "#{emoji} [#{count}]"
  end

end