class Panel::PersonalJournal::Desktop::JournalCoAuthorsController < ApplicationController
  def index
    page = params[:page]
    page ||= 1
    @journal_co_authors = JournalCoAuthor.where(name_id: current_user.id).asc(:co_author)
    @journal_co_author_relations = JournalCoAuthorRelation.all

    @journal_co_authors = @journal_co_authors.page(page).per(40)

    respond_to do |format|
      format.html { render :layout => false}
    end
  end

  def new
    @journal_co_author = JournalCoAuthor.new
    @journal_co_author_relations = JournalCoAuthorRelation.all

    respond_to do |format|
      format.html { render :layout => false}
    end
  end

  def edit
    @journal_co_author = JournalCoAuthor.find(params[:id])
    @journal_co_author_relations = JournalCoAuthorRelation.all
    respond_to do |format|
      format.html { render :layout => false}
    end
  end

  def create
    @journal_co_author = JournalCoAuthor.new(params[:journal_co_author])
    @journal_co_author.name_id= current_user.id

    if @journal_co_author.save
      render json: {success:true, msg: t('create_success')}.to_json
    else
      error_msg = @journal_co_author.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def update
    @journal_co_author = JournalCoAuthor.find(params[:id])

    if @journal_co_author.update_attributes(params[:journal_co_author])
      render json: {success:true, msg: t('update_success')}.to_json
    else
      error_msg = @journal_co_author.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def destroy
    @journal_co_author = JournalCoAuthor.find(params[:id])
    @journal_co_author.destroy

    render :json => {success: true, msg: "delete_success"}
  end
end
