class EasyMeetingsController < ApplicationController

  accept_api_auth :create

  before_action :find_easy_meeting, :only => [:show, :edit, :update, :destroy, :accept, :decline]

  def new
    @easy_meeting = EasyMeeting.new
    @easy_meeting.safe_attributes = params[:easy_meeting] if params[:easy_meeting]
    render :layout => !request.xhr?
  end

  def create
    @easy_meeting = EasyMeeting.new
    @easy_meeting.safe_attributes = params[:easy_meeting]
    if @easy_meeting.save
      respond_to do |format|
        format.html {
          flash[:notice] = l(:notice_successful_create)
          redirect_to :action => 'new'
        }
        format.api {render_api_ok}
      end
    else
      respond_to do |format|
        format.html {render :action => 'new'}
        format.api {render_validation_errors @easy_meeting}
      end
    end
  end

  def edit
    respond_to do |format|
      format.html {render :layout => !request.xhr?}
      format.js
    end
  end

  def update
    @easy_meeting.safe_attributes = params[:easy_meeting] if params[:easy_meeting]
    if @easy_meeting.save
      respond_to do |format|
        format.html{
          flash[:notice] = l(:notice_successful_update)
          redirect_to :action => 'show'
        }
        format.api {render_api_ok}
      end
    else
      respond_to do |format|
        format.html {render :action => 'edit'}
        format.api {render_validation_errors @easy_meeting}
      end
    end
  end

  def show
    respond_to do |format|
      format.html {render :layout => !request.xhr?}
      format.js
    end
  end

  def destroy
    if params[:repeating] || @easy_meeting.big_recurring?
      @easy_meeting.destroy_all_repeated
    else
      @easy_meeting.destroy
    end
    respond_to do |format|
      format.api {render_api_ok}
    end
  end

  def accept
    @easy_meeting.accept!
    respond_to do |format|
      format.html {
        flash[:notice] = l(:notice_successful_update)
        redirect_to :action => 'show'
      }
      format.api {render_api_ok}
    end
  end

  def decline
    @easy_meeting.decline!
    respond_to do |format|
      format.html {
        flash[:notice] = l(:notice_successful_update)
        redirect_to :action => 'show'
      }
      format.api {render_api_ok}
    end
  end

  private

  def find_easy_meeting
    @easy_meeting = EasyMeeting.find(params[:id]) if params[:id]
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end
