class Desktop::CoAuthorRelationsController < ApplicationController
  def index
    @co_author_relations = CoAuthorRelation.all
    new

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

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

  def new
    @co_author_relation = CoAuthorRelation.new
  end

  def create
    @co_author_relation = CoAuthorRelation.new(params[:co_author_relation])
    @co_author_relations = CoAuthorRelation.all

    if @co_author_relation.save
      newv = render_to_string partial: "show_form", object: @co_author_relations
      render json: {success: true, msg: "New Relation successfully saved!", newvalue: newv}.to_json
    else
      error_msg = @co_author_relation.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def update
    @co_author_relation = CoAuthorRelation.find(params[:id])
    if @co_author_relation.update_attributes(params[:co_author_relation])
      @co_author_relations = CoAuthorRelation.all
      newv = render_to_string partial: "show_form", object: @co_author_relations
      render json: {success: true, msg: "New Relation successfully updated!", newvalue: newv}.to_json
    else
      error_msg = @co_author.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def destroy
    @co_author_relation = CoAuthorRelation.find(params[:id])
    @co_author_relation.destroy
    reset_co_author_relation

    render :json => {success: true, msg: "deleted successfully!"}
  end

  private

  def reset_co_author_relation
    co_author = CoAuthor.where(co_author_relations_id: @co_author_relation.id)
    co_author.map do |c|
      c.update_attributes(co_author_relations_id: nil)
    end
  end
end
