module Users
  class OrdersController < Users::ApplicationController
    respond_to :json

    # Used by the user Ember app
    def create
      render json: {}, status: :unprocessable_entity and return unless params[:order].present? && params[:order][:product_orders].present?
      converted_order = params[:order][:product_orders].each_with_object({}){|po, o| o[po[:product_id]] = po[:quantity] }
      if list = current_user.active_list
        render json: {}, status: :not_acceptable and return unless list.supplier.open?
      else
        render json: {}, status: :unprocessable_entity and return unless params[:order][:table_id].present?
        table = Table.find(params[:order][:table_id])
        render json: {}, status: :not_acceptable and return unless table.supplier.open?

        if table.occupied?
          #render json: json_alert('messages.table_is_occupied', location: :join_occupied_table, location_params: {table_id: @table.id})
          render json: {}, status: :not_acceptable and return
        end

        list = List.from_table( table, current_user )
      end
      order = list.place_order products: converted_order, user: current_user
      render json: order, serializer: OrderSerializer
    end
  end
end
