class NotesController < ApplicationController
  before_action :set_note, only: [:show, :update, :destroy]
  before_action :ensure_valid_user

  # GET /notes
  # GET /notes.json
  def index
    @notes = Note.for_user(current_user)
    render json: NoteSerializer.for(@notes)
  end

  # GET /notes/1
  # GET /notes/1.json
  def show
    ensure_owner(@note)
    render json: NoteSerializer.for(@note)
  end

  # POST /notes
  # POST /notes.json
  def create
    @note = Note.new(note_params)
    @note.user = current_user

    respond_to do |format|
      if @note.save
        format.html { redirect_to notes_path, notice: 'Note was successfully created.' }
        format.json { render json: NoteSerializer.for(@note), status: :created, location: @note }
      else
        format.html { render :new }
        format.json { render json: @note.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /notes/1
  # PATCH/PUT /notes/1.json
  def update
    ensure_owner(@note) do
      respond_to do |format|
        if @note.update(note_params)
          format.html { redirect_to notes_path, notice: 'Note was successfully updated.' }
          format.json { render json: NoteSerializer.for(@note), status: :ok, location: @note }
        else
          format.html { render :edit }
          format.json { render json: @note.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  # DELETE /notes/1
  # DELETE /notes/1.json
  def destroy
    ensure_owner(@note) do
      @note.destroy
      respond_to do |format|
        format.html { redirect_to notes_url, notice: 'Note was successfully destroyed.' }
        format.json { head :no_content }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_note
      @note = Note.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def note_params
      params.require(:note).permit(:content)
    end
end
