class Panel::PersonalConference::Desktop::ConferenceCoAuthorRelationsController < ApplicationController
  def index
    page = params[:page]
    page ||= 1
    @conference_co_author_relations = ConferenceCoAuthorRelation.all
    new

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

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

  def new
    @conference_co_author_relation = ConferenceCoAuthorRelation.new
  end

  def create
    @conference_co_author_relation = ConferenceCoAuthorRelation.new(params[:conference_co_author_relation])
    @conference_co_author_relations = ConferenceCoAuthorRelation.all

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

  def update
    @conference_co_author_relation = ConferenceCoAuthorRelation.find(params[:id])
    if @conference_co_author_relation.update_attributes(params[:conference_co_author_relation])
      @conference_co_author_relations = ConferenceCoAuthorRelation.all
      newv = render_to_string partial: "show_form", object: @conference_co_author_relations
      newv = '<div class="overview" content-layout="datalist" per-column="4" base-width="300">' + newv + '</div>'
      render json: {success: true, msg: t('update_success'), newvalue: newv}.to_json
    else
      error_msg = @conference_co_author.errors.full_messages.join("<br />")
      render json: {success: false, msg: error_msg}.to_json
    end
  end

  def destroy
    @conference_co_author_relation = ConferenceCoAuthorRelation.find(params[:id])
    @conference_co_author_relation.destroy
    reset_co_author_relation

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

  private

  def reset_co_author_relation
    co_author = ConferenceCoAuthor.where(conference_co_author_relations_id: @conference_co_author_relation.id)
    co_author.map do |c|
      c.update_attributes(conference_co_author_relations_id: nil)
    end
  end
end
