class SettingsController < ApplicationController
  before_filter :require_login

  add_breadcrumb "Dashboard", :dashboard_path

  # Get the current user.
  def show
    @user = current_user
  end

  # To edit the user profile information (i.e. educations,awards,positions)
  def edit
    add_breadcrumb "Edit Profile", :edit_settings_path
    @user = current_user
    @user.educations.build unless @user.educations.exists?
    @user.awards.build unless @user.awards.exists?
    @user.positions.build unless @user.positions.exists?
    if params[:partial].present?
      render partial: "#{params[:partial]}", locals: {user: @user}, layout: false
    end
  end

  # To update user related information.
  def update
    @user = current_user
    respond_to do |format|
      if params[:form_type] == 'change_password'
        if @user.valid_password?(params[@user.type.downcase.to_sym][:current_password]) || !@user.crypted_password?
          if params[@user.type.downcase.to_sym][:password] == params[@user.type.downcase.to_sym][:password_confirmation]
            @user.password = params[@user.type.downcase.to_sym][:password]
            @user.password_confirmation = params[@user.type.downcase.to_sym][:password_confirmation]
            @user.valid?
            if @user.errors[:password].empty?
              @user.save
              UserMailer.delay(queue: :mailer).password_update_email(@user.id)
              @message = 'Password updated successfully.'
              format.js
            else
              @message = 'Password was not updated.'
              format.js
            end
          else
            @message = 'Confirm password is not similar to the new password.'
            format.js
          end
        else
          @message = 'Old password is not valid.'
          format.js
        end
      else
        if @user.update_attributes(user_params)
          if params[:type] == 'popover'
            @message = "#{params[:form_type].titleize} was updated successfully."
            format.js
          else
            @message = "#{params[:type].titleize} was updated successfully." if params[:type]
            if params[:type] == 'availability'
              format.js
            else
              format.html { redirect_to dashboard_path, notice: @message}
              format.js { redirect_via_turbolinks_to dashboard_path, notice: @message}
              format.json {render json: {}}
            end
          end
        else
          if params[:type] == 'popover'
            @message = "#{params[:form_type].titleize} was not updated."
            format.js
          else
            message = "#{params[:type].titleize} was not updated." if params[:type]
            format.html { redirect_to params[:type] == 'availability' ? personal_calendar_path : dashboard_path, notice: message}
            format.js { redirect_via_turbolinks_to params[:type] == 'availability' ? personal_calendar_path : dashboard_path, notice: message}
            format.json { render json: @user.errors[:rate_in_cents].present? ? @user.errors[:rate_in_cents].join(', ') : @user.errors.full_messages.join(','), status: :unprocessable_entity }
          end
        end
      end
    end
  end

  # To build credit card and bank account if not present.
  def payment_details
    @user = current_user
    @user.credit_cards.build unless @user.credit_cards.exists?
    @user.build_bank_account unless @user.bank_account
    render layout: false
  end

  # To update the credit card and bank account details of user.
  def update_payment_details
    @user = current_user
    respond_to do |format|
      format.js do
        if @user.update_attributes(user_params)
          render 'update_payment_details'
        else
          render partial: params[:type], locals: {user: @user}, replace: "##{params[:type]}"
        end
      end
    end
  end

  # Remove current avatar
  def destroy_avatar
    if current_user.profile_image.present? and current_user.profile_image.destroy
      flash[:notice] = "Your avatar has been removed."
    else
      flash[:alert] = "We were unable to remove your avatar."
    end
    redirect_to edit_settings_path
  end

  private

  def user_params
    required_params = params.required(@user.type.try(:downcase)) rescue {}
    required_params = params.required(:user) if required_params.blank?
    required_params.permit(
      :name, :headline, :industry, :location, :summary, :last_name, :exp_title, :rate,
      :response_time, :course_ids, :phone,
      educations_attributes: [
        :school_name, :degree, :field_of_study, :minor, :description,
        :_destroy, :start_date, :end_date, :id
      ],
      awards_attributes: [
        :name, :issuer, :date_received, :description, :_destroy, :id
      ],
      positions_attributes: [
        :university_name, :title, :start_date, :end_date, :is_current,
        :location, :description, :_destroy, :id
      ],
      credit_cards_attributes: [
        :number, :name, :token, :active, :exp_month, :exp_year, :cvv, :id, :_destroy
      ],
      bank_account_attributes: [
        :name_on_account, :account_number, :account_number_confirmation, :token, :active, :routing_number, :country, :currency, :_destroy, :id
      ],
      availabilities_attributes: [
        :start_time_hr, :start_time_min, :end_time_hr, :end_time_min, :day, :id, :_destroy
      ]
     ) rescue {}
  end
end
