# frozen_string_literal: true


module PostRepr
  BASE_FIELDS = [
      :id,
      :version_no,
      :url,
      :title,
      :thumbnail_base,
      :video_ms,
      :original_created_from,
      :original_created_before,
      :created_at,
      :updated_at
  ].freeze

  module_function

  def base post, current_user = nil
    json = common(post)
    json['tags'] = tag_json(post)
    json['uploaded_user'] = post.uploaded_user && UserRepr.base(post.uploaded_user)
    json['viewed'] = current_user ? current_user.viewed?(post) : false
    json
  end

  def detail post, current_user = nil, parent_posts: [], child_posts: [],
             sibling_posts: { }, related: []
    base(post, current_user).merge(
        'parent_posts' => cards(parent_posts),
        'child_posts' => cards(child_posts),
        'sibling_posts' => sibling_posts.transform_keys(&:to_s).transform_values { |posts|
          cards(posts)
        },
        'related' => cards(related))
  end

  def card post
    common(post).merge('parent_posts' => [], 'child_posts' => [])
  end

  def cards posts
    posts.map { |post| card(post) }
  end

  def many posts, current_user = nil
    posts.map { |p| base(p, current_user) }
  end

  def common post
    BASE_FIELDS.to_h { |field| [field.to_s, post.public_send(field)] }
               .merge('thumbnail' => thumbnail_url(post))
  end

  def tag_json post
    post
        .active_post_tags
        .reject { _1.tag.deprecated? }
        .sort_by { _1.tag.name }
        .map { |post_tag|
      TagRepr.inline(post_tag.tag).merge(
          'children' => [],
          'sections' => post_tag.sections.as_json(only: [:begin_ms, :end_ms]))
    }
  end

  def thumbnail_url post
    return nil unless post.thumbnail.attached?

    Rails.application.routes.url_helpers.rails_blob_url(post.thumbnail, only_path: false)
  rescue ActionController::UrlGenerationError, ArgumentError, URI::InvalidURIError => e
    Rails.logger.warn(
        "PostRepr.thumbnail_url failed post_id=#{post.id} " \
        "attachment_id=#{post.thumbnail.attachment&.id} " \
        "blob_id=#{post.thumbnail.blob&.id} " \
        "error_class=#{e.class} message=#{e.message}")
    nil
  end
end
