class Admin::Admissions::Families::Current::ContactsController < Admin::Admissions::Controller
  include Admin::Admissions::FamilyScoped

  def index
    render_success :ok, json: contacts.map { |c| contact_props(c) }
  end

  def show
    render_success :ok, json: contact_props(contact)
  end

  def update
    if contact.update(contact_params)
      render_success :ok, json: contact_props(contact)
    else
      render_error :unprocessable_entity, errors: contact
    end
  end

  private
    def contacts
      family.contacts
    end

    def contact
      @contact ||= contacts.find_by(id: params[:id])
    end

    def contact_families_by_contact
      @contact_families_by_contact ||= family.contact_families.index_by(&:contact_id)
    end

    def contact_params
      params.permit(
        :first_name,
        :last_name,
        :title_id,
        :address,
        :address_ext,
        :city,
        :state,
        :zip,
        :country_id,
        :home_phone,
        :work_phone,
        :cell_phone,
        :email,
        contact_families_attributes: [
          :id,
          :relationship_id,
          :pickup,
          :emergency,
          :primary
        ]
      )
    end

    def contact_props(contact)
      contact_family = contact_families_by_contact[contact.id]
      {
        id: contact.id,
        full_name: contact.full_name(:reverse),
        first_name: contact.first_name,
        last_name: contact.last_name,
        title_id: contact.title_id? ? contact.title_id : nil,
        address: contact.address,
        address_ext: contact.address_ext,
        city: contact.city,
        state: contact.state,
        zip: contact.zip,
        country_id: contact.country_id? ? contact.country_id : nil,
        work_phone: contact.work_phone,
        home_phone: contact.home_phone,
        cell_phone: contact.cell_phone,
        email: contact.email,
        contact_family_id: contact_family.id,
        primary: contact_family.primary?,
        emergency: contact_family.emergency?,
        pickup: contact_family.pickup?,
        relationship_id: contact_family.relationship_id? ? contact_family.relationship_id : nil,
        contact_families_attributes: {
          id: contact_family.id,
          primary: contact_family.primary?,
          emergency: contact_family.emergency?,
          pickup: contact_family.pickup?,
          relationship_id: contact.country_id? ? contact.country_id : nil
        }
      }
    end
end
