class DraftsController < ApplicationController
  before_action :set_draft, except: %i(index new create)
  authorize_resource

  def index
    if !signed_in?
      @drafts = []
    elsif current_user.is_admin?
      @drafts = Draft.all.page(params[:page])
    else # normal user
      @drafts = Draft.where(user_id: current_user.id).page(params[:page])
    end
    respond_with(@drafts)
  end

  def show
    respond_with(@draft, layout: 'preview')
  end

  def new
    if cookies[:draft_key].present? && !%w(1 t).member?(params[:new])
      @draft = Draft.find_by(key: cookies[:draft_key])
    end
    @draft ||= Draft.create user: current_user
    cookies.permanent[:draft_key] = @draft.key
    redirect_to edit_draft_path(@draft)
  end

  def edit
    cookies.permanent[:draft_key] = @draft.key
  end

  def create
    @draft = Draft.new(draft_params)
    @draft.save
    respond_with(@draft)
  end

  def update
    @draft.update(draft_params)
    respond_with(@draft)
  end

  def destroy
    @draft.destroy
    respond_with(@draft)
  end

  private
  def set_draft
    @draft = Draft.find_by!(key: params[:id])
  end

  def draft_params
    params.require(:draft).permit(:title, :url, :day_frame, *Draft::ICONS.map{|i| "wi_#{i}"})
  end
end
