class Support::LeafNotesController < Support::ApplicationController
  include DateRangeHelper

  def show
    render_success :ok, json: props(note)
  end

  def index
    render_success :ok, json: notes.map { |n| props(n) }
  end

  def create
    note = notes.build(note_params)

    if note.save
      render_success :ok, json: props(note)
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  def update
    if note.update(note_params)
      render_success :ok, json: props(note)
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  def destroy
    if note.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  def update_schools
    if note.update(schools: schools)
      render_success :ok, json: props(note)
    else
      render_error :unprocessable_entity, errors: note
    end
  end

  private
    def notes
      @notes ||= Communication::LeafNote.all
        .preload(:leaf_note_users)
        .by_date_range(datetime_range(params[:date_range]))
    end

    def note
      Communication::LeafNote.find(params[:id])
    end

    def schools
      School.all.where(id: params[:school_ids])
    end

    def area
      'communication'
    end

    def note_params
      params.permit(
        :title,
        :expire_date,
        :limited,
        :viewable,
        :content,
        :to_superusers
      )
    end

    def props(note)
      {}.tap do |props|
        props[:id] = note.id
        props[:title] = note.title
        props[:date] = note.date
        props[:expire_date] = note.expire_date
        props[:limited] = note.limited?
        props[:viewable] = note.viewable?
        props[:to_superusers] = note.to_superusers?
        props[:view_count] = note.leaf_note_users.size
        return props if action_name == 'index'
        props[:content] = note.content
        props[:schools] = note.schools.map { |s| { id: s.id } }
      end
    end
end
