class Panel::PersonalJournal::Desktop::JournalCoAuthorRelationsController < ApplicationController
  def index
    page = params[:page]
    page ||= 1
    @journal_co_author_relations = JournalCoAuthorRelation.all
    new

    @journal_co_author_relations = @journal_co_author_relations.page(page).per(50)
    respond_to do |format|
      format.html {render layout: false }
    end
  end

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

  def new
    @journal_co_author_relation = JournalCoAuthorRelation.new
  end

  def create
    @journal_co_author_relation = JournalCoAuthorRelation.new(params[:journal_co_author_relation])
    @journal_co_author_relations = JournalCoAuthorRelation.all

    if @journal_co_author_relation.save
      newv = render_to_string partial: "show_form", object: @journal_co_author_relations
      render json: {success: true, msg: t("create_success"), newvalue: newv}.to_json
    else
      error_msg = @journal_co_author_relation.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def update
    @journal_co_author_relation = JournalCoAuthorRelation.find(params[:id])
    if @journal_co_author_relation.update_attributes(params[:journal_co_author_relation])
      @journal_co_author_relations = JournalCoAuthorRelation.all
      newv = render_to_string partial: "show_form", object: @journal_co_author_relations
      render json: {success: true, msg: t("update_success"), newvalue: newv}.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_relation = JournalCoAuthorRelation.find(params[:id])
    @journal_co_author_relation.destroy
    reset_co_author_relation

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

  private

  def reset_co_author_relation
    co_author = JournalCoAuthor.where(journal_co_author_relations_id: @journal_co_author_relation.id)
    co_author.map do |c|
      c.update_attributes(journal_co_author_relations_id: nil)
    end
  end
end
