# frozen_string_literal: true

# En mantenimiento
class Maintenance < ApplicationRecord
  extend Mobility

  translates :message, type: :string, locale_accessors: true

  # Renderiza el mensaje una sola vez
  #
  # @return [String]
  def to_html
    @renderized_message ||= {}
    @renderized_message[message.hash.to_s] ||= CommonMarker.render_doc(message, %i[FOOTNOTES SMART], %i[table strikethrough autolink]).to_html.html_safe
  end

  # Como no sabemos en qué zona horaria están les usuaries, generamos la
  # URL para convertir el tiempo estimado a la zona local, visitando
  # otro servicio.
  #
  # @return [String]
  def estimated_from_time_is
    @estimated_from_time_is ||= {}
    @estimated_from_time_is[cache_key_for_attr(estimated_from)] ||= time_is(estimated_from)
  end

  # @see estimated_from_time_is
  # @return [String]
  def estimated_to_time_is
    @estimated_to_time_is ||= {}
    @estimated_to_time_is[cache_key_for_attr(estimated_to)] ||= time_is(estimated_to)
  end

  # @see estimated_from_time_is
  # @return [String]
  def updated_at_time_is
    @updated_at_time_is ||= {}
    @updated_at_time_is[cache_key_for_attr(updated_at)] ||= time_is(updated_at)
  end

  private

  def cache_key_for_attr(attr)
    attr.hash.to_s + I18n.locale.to_s
  end

  # Devuelve la URL
  #
  # @param [Time]
  # @return [String]
  def time_is(time)
    "https://time.is/#{I18n.locale}/compare/#{time.utc.strftime('%H%M_%d_%B_%Y_in_%Z')}"
  end
end