class Panel::PersonalBook::Desktop::PersonalBooksController < ApplicationController

	def index
    @writing_books = WritingBook.where(create_user_id: current_user.id)
    @view_by = params[:view]
    page = params[:page]
    page ||= 1

    @per_column = 5

    case @view_by
    when "abstract"
      @per_column = 1
    when "file"
      @per_column = 2
    end

    if @view_by.nil?
      @view_by = " " 
      @writing_books = @writing_books.asc(:paper_title)
    else
      @writing_books = @writing_books.asc(@view_by).asc(:paper_title)
    end
    @writing_books = @writing_books.page(page).per(50)
		respond_to do |format|
    	format.html { render :layout => false}
    end
	end

  def new
    @personal_book = WritingBook.new
    @author_types = BookAuthorType.all
    render :layout => false
  end

  def create
    params[:writing_book][:create_user_id] = current_user.id
    @personal_book = WritingBook.new(params[:writing_book])
    if @personal_book.save
      render json: {success: true, msg: t('create_success')}.to_json
    else
      error_msg = @personal_book.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def edit
    @personal_book = WritingBook.find(params[:id])
    @author_types = BookAuthorType.all
    render :layout => false
  end

  def update
    params[:writing_book][:create_user_id] = current_user.id
    @personal_book = WritingBook.find(params[:id])
    if @personal_book.update_attributes(params[:writing_book])
      render json: {success: true, msg: t('create_success')}.to_json
    else
      error_msg = @personal_book.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def destroy 
    @personal_book = WritingBook.find(params[:id])
    @personal_book.destroy
    render :json => {success: true, msg: t('delete_success')}
  end

  def books_window
    render :layout => false
  end
end