class MobileAppApi::V1::RegistrationController < MobileAppApi::V1::BaseController
before_filter :login_required!, :except => [:sign_up]

  # Method to signup manually from mobile app i.e. create new user account with its mail Id.
  def sign_up
    params[:user].permit!
    user = User.new params[:user], as: :creator
    if user.save
      user.generate_auth_token
      render json: { status: 200, is_valid_user: user.valid?, user_info: user, auth_token: user.auth_token }
    else
      render json: { status: 400, error: "Sign up process failed.", is_valid_user: user.valid?, error_details: user.errors.full_messages }
    end
  end

  # Method to activate the user signup manually through clicking its email link.
  def update_billing_shipping_details
    result = User.update_all(
      {
        :billing_address_1 => params[:billing_address_1],
        :billing_address_2 => params[:billing_address_2],
        :billing_city => params[:billing_city],
        :billing_state => params[:billing_state],
        :billing_zipcode => params[:billing_zipcode],
        :shipping_address_1 => params[:shipping_address_1],
        :shipping_address_2 => params[:shipping_address_2],
        :shipping_city => params[:shipping_city],
        :shipping_state => params[:shipping_state],
        :shipping_zipcode => params[:shipping_zipcode]
      },
      {:id => user[0].id}
    )
    if result == 1
      render json: { status: 200 }
    else
      render json: { status: 400, error: "Update failed." }
    end
  end

  # Method to get credit card details of the current user.
  def get_credit_cards
    credit_card_details = @user.credit_cards
    if credit_card_details
      render json: { status: 200, credit_card_details: credit_card_details.map{|c| c.attributes.except('uri', 'created_at', 'updated_at', 'company_id')}}
    else
      render json: { status: 401, error: "Credit card for user #{@user.name} not found." }
    end
  end

  # Method to add credit card details for the current user.
  def add_credit_card
    @credit_card = @user.credit_cards.build(credit_card_params)
    @credit_card.active = true
    if @credit_card.save
      render json: {status: 200, success: "Successfully created card."}
    else
      render json: {status: 401, error: "Invalid card details."}
    end
  end

  # Method to activate the credit card when added by user.
  def activate_credit_card
    @credit_card = @user.credit_cards.find(params[:id])
    @credit_card.active = true
    if @credit_card.save
      render json: {status: 200, :success => "Card successfully activated."}
    else
      render json: {status: 401, error: "Invalid card details."}
    end
  end

  # Method to remove the credit card from user account.
  def remove_credit_card
    @credit_card = @user.credit_cards.find(params[:id])
    if @credit_card.destroy
      render json: {status: 200, :success => "Successfully destroyed card."}
    else
      render json: {status: 401, error: "Can't destroy card."}
    end
  end

  # Method to upadate and create bank account for current user.
  def update_bank_details
    if Payment.create_new_bank params[:payment], @user
      render json: {status: 200, :success => "Successfully created bank account."}
    else
      render json: {status: 400, error: "Invalid bank details."}
    end
  end

  #"payment" =>
  # {
  #   "name"=>"Kiran Sarode",
  #   "bank_code"=>"021000021",
  #   "account_number"=>"9900000002",
  #   "type"=>"SAVINGS"
  # }

  # Method to find all subtrades of trades with trade Id.
  def get_subtrades_for_trade
    trade = Trade.find(params[:trade_id])
    if !trade.nil?
      subtrades = trade.subtrades
      render json: {status: 200, :subtrades => subtrades, :total_subtrades => subtrades.length}
    else
      render json: {status: 400, error: "Trade with trade_id #{params[:trade_id]} not found."}
    end
  end

  # Method to add subtrade to fixxpert account.
  def add_subtrades
    fixxpert = Fixxpert.where(auth_token: params[:auth_token])
    if !fixxpert.nil? && !fixxpert[0].nil?
      trade_fixxperted = TradesFixxpert.where(:trade_id => params[:trade_id], :fixxpert_id => fixxpert[0].id)
      if(!trade_fixxperted.nil? && !trade_fixxperted[0].nil?)
      else
        st = TradesFixxpert.new(:trade_id => params[:trade_id], :fixxpert_id => fixxpert[0].id)
        st.save
      end
      if params[:selected_subtrade_ids].kind_of?(Array)
        params[:selected_subtrade_ids].each do |subtrade_id|
          begin
            subtrade = Subtrade.find subtrade_id
          rescue => e
            render json: {status: 400, error: "Subtrade with id #{subtrade_id} not found."}
            return
          end
          if subtrade
            Fixxpert.find(fixxpert[0].id).subtrades << subtrade unless Fixxpert.find(fixxpert[0].id).subtrades.include?(subtrade)
          else
            render json: {status: 400, error: "Subtrade with id #{subtrade_id} not found."}
            return
          end
        end
        render json: {status: 200}
      else
        render json: {status: 400, error: "Array of subtrade ids not found in parameters, please check subtrade id array and try again."}
        return
      end
    else
      render json: {status: 400, error: "Fixxpert with auth_token #{params[:auth_token]} not found."}
    end
  end

  # To update user profile
  def update_profile
    if @user.type == "Fixxpert"
      if user[0].update_attributes params[user[0].type_to_symbol], as: :creator
        render json: { status: 200 }
      else
        render json: { status: 400, error: "Update failed." }
      end
    else
      if user[0].update_attributes params[user[0].type_to_symbol], as: :creator
        render json: { status: 200 }
      else
        render json: { status: 400, error: "Update failed." }
      end
    end
  end

  private
    def credit_card_params
      params.required(:credit_card).permit(:number, :name, :expiry_date, :cvv, :active, :id, :_destroy)
    end

end
