class School::Legacy::NewsArticlesController < ApplicationController
  def index
    articles = news_articles.preload(:news_readers, :classroom).ordered
    articles = articles.reject { |a| future_article?(a) && !permissions?(a) }

    if params[:scope].to_sym == :class && role != :employee
      articles = articles.reject { |a| not_viewable_by_parent?(a) }
    end

    objects = articles.map { |a| article_props(a) }
    render_success :ok, json: objects
  end

  def show
    reader = article.news_readers.find_or_initialize_by(user: current_user, school: current_school)
    reader.mobile = 1 if reader.new_record?
    reader.save

    props = if article.parent_article
      article_props(article).merge(content: article.parent_article.content)
    else
      article_props(article).merge(content: article.content)
    end
    render_success :ok, json: props
  end

  private
    def news_articles
      current_user.news_articles_by_scope(params[:scope]&.to_sym)
        .preload(:parent_article)
        .read_or_unread(params[:read]&.to_bool)
        .with_classroom_id(params[:classroom_id])
        .archived(params[:archived])
        .recent(params[:recent]&.to_bool)
        .exclude_future
        .distinct
    end

    def article
      @article ||= news_articles.find(params[:id])
    end

    def article_props(article)
      {}.tap do |props|
        props[:id] = article.id
        props[:title] = article.title
        props[:date] = article.decorate.date
        props[:read] = article.news_readers.any?
        props[:class_name] = article.classroom.name if article.classroom
        props[:top_story] = article.top_story?
        props[:recent] = article.Date > 3.months.ago
        return props unless action_name.to_sym == :show

        props[:author] = article.decorate.user_full_name(:reverse)
        props[:documents] = article.documents.map { |d| document_props(d) }
      end
    end

    def document_props(document)
      {
        id: document.id,
        name: document.name,
        file: document.extension
      }
    end

    def future_article?(article)
      article.datetime > Time.zone.now
    end

    def permissions?(article)
      return true if current_user.superuser

      if article.class_id.zero?
        @school_permission ||= current_user.has_permission('CoNews')
      else
        current_user.level.positive?
      end
    end

    def not_viewable_by_parent?(article)
      article.classroom.parent_viewable.zero?
    end
end
