class Oqs::HomeController < BaseOqsController
  authorize_resource :class => false
  def index
    # Query for OQS with delivery status false
  	# @queue_items_details = queue_items_query(false)

    # Query for OQS with delivery status true
    # @tables   = DiningFacility.all.active.order('status desc')
    @tables   = DiningFacility.where(:type => 'Table').order('status desc')
    @rooms    = Room.all.active.order('status desc')

    @filter = params[:filter]

    @queue_stations = OrderQueueStation.all
   
    @queue_completed_item = completed_order(@filter)
    if !@queue_completed_item.empty?
      @queue_completed_item.each do |queue_item|
        if !queue_item.set_menu_items.nil?
          instance_item_sets = JSON.parse(JSON.parse(queue_item.set_menu_items))
          arr_instance_item_sets = Array.new
          instance_item_sets.each do |instance_item|
            item_instance_name = MenuItemInstance.find_by_item_instance_code(instance_item["item_instance_code"]).item_instance_name
            arr_instance_item_sets.push(item_instance_name)
          end
          queue_item.set_menu_items = arr_instance_item_sets
        end
      end
    end

    if !@filter.nil?
      @count = queue_items_count_query(false,@filter)
      #@count.each do |count|

      #end
    end

    # @queue_stations_items=Array.new

    # Calculate Count for each station tab
    # @queue_stations.each do |que|
    #   i = 0
    #   zone_id = 0
    #   @queue_items_details.each do |qid|
    #     dining = DiningFacility.find_by_name(qid.zone)
    #     que.order_queue_process_by_zones.each do |qz|
    #       if qid.station_id == qz.order_queue_station_id && qid.zone_id == qz.zone_id
    #         zone_id = qid.zone_id
    #         i=i+1
    #       end
    #     end        
    #   end
    #   @queue_stations_items.push({:zone_id => zone_id  , :station_name => que.station_name, :is_active => que.is_active , :is_ap => que.auto_print, :item_count => i })
    # end

    # # @queue_items_details = @queue_items_details.paginate(:per_page => 10, :page => params[:page])
    # @queue_stations_items
  end

  # Get Order items
  def get_order_items
    items = []
    assigned_items = []
    order_no = params[:order_no]
    status = params[:status]
    # dining = DiningFacility.find_by_name(table_name);
    # oqpz = OrderQueueProcessByZone.find_by_zone_id(dining.zone_id)
    # if status == ""
    #   AssignedOrderItem.where("order_queue_station_id=#{ oqpz.order_queue_station_id } AND delivery_status=0").find_each do |aoi|
    #     oi = OrderItem.find_by_item_code(aoi.item_code)
    #     items.push(oi)
    #   end
    # else
    #   AssignedOrderItem.where("order_queue_station_id=#{ oqpz.order_queue_station_id } AND delivery_status=1").find_each do |aoi|
    #     oi = OrderItem.find_by_item_code(aoi.item_code)
    #     items.push(oi)
    #   end
    # end

    # booking = Booking.find_by_dining_facility_id(dining.id)
    # BookingOrder.where("booking_id='#{ booking.booking_id }'").find_each do |bo|
    #   order=Order.find(bo.order_id)
    #   order.order_items.each do |oi|
    #     items.push(oi)
    #   end
    # end

    OrderItem.where("order_id='#{ order_no }'").find_each do |oi|
      items.push(oi)
    end

    if !items.empty?
      items.each do |item|
        assigned_order_items = AssignedOrderItem.find_by_item_code_and_instance_code_and_order_id(item.item_code,item.item_instance_code,item.order_id)
        if !assigned_order_items.nil?
          assigned_items.push({item.order_items_id => assigned_order_items.assigned_order_item_id})
        end

        if !item.set_menu_items.nil?
          instance_item_sets = JSON.parse(item.set_menu_items)
          arr_instance_item_sets = Array.new
          instance_item_sets.each do |instance_item|
            item_instance_name = MenuItemInstance.find_by_item_instance_code(instance_item["item_instance_code"]).item_instance_name
            arr_instance_item_sets.push(item_instance_name)
          end
          item.set_menu_items = arr_instance_item_sets
        end
      end
    end
    render :json => {'items' => items, 'assigned_order_items' => assigned_items }
  end

  def get_items_by_oqs
    oqs_id = params[:id]
    filter = params[:filter]
    table_id = params[:table_id]
    puts params
    puts table_id
    puts "sssssssssssss"
    items  = queue_items_query(false,oqs_id,filter,table_id)
    if !items.empty?
      items.each do |item|
        if !item.set_menu_items.nil?
          instance_item_sets = JSON.parse(JSON.parse(item.set_menu_items))
          arr_instance_item_sets = Array.new
          instance_item_sets.each do |instance_item|
            item_instance_name = MenuItemInstance.find_by_item_instance_code(instance_item["item_instance_code"]).item_instance_name
            arr_instance_item_sets.push(item_instance_name)
          end
          item.set_menu_items = arr_instance_item_sets
        end
      end
    end
    render :json => items.to_json
  end

  def show
  end

  # update delivery status when complete click
  def update_delivery_status
    removed_item = []
    assigned_item_id = params[:id]
    assigned_item=AssignedOrderItem.find(assigned_item_id)
    assigned_items=AssignedOrderItem.where("item_code='" + assigned_item.item_code + "' AND " + "order_id='" + assigned_item.order_id + "'");

    # update delivery status for completed same order items
    assigned_items.each do |ai|
      ai.delivery_status=true
      ai.save
      removed_item.push(ai.assigned_order_item_id)
    end
    render :json => removed_item.to_json
  end


  # Query for OQS with delivery status
  def queue_items_query(status,oqs_id=nil,filter,table_id) 
    if oqs_id == nil
       oqs = ''
    else
      oqs = "and assigned_order_items.order_queue_station_id = '#{oqs_id}' "
    end

    if !table_id.empty?
       tableId = table_id.to_a.map{|h| h}.join(",")
       table = "and df.id IN (#{tableId})"
    else
     table = ''
    end

    query = AssignedOrderItem.select("assigned_order_items.assigned_order_item_id, 
                              oqs.id as station_id, oqs.station_name, 
                              oqs.is_active, oqpz.zone_id, 
                              df.name as zone, df.type as table_type, 
                              odt.order_id, odt.item_code, odt.item_name, 
                              odt.price, odt.qty, odt.item_order_by, odt.options, odt.set_menu_items, 
                              cus.name as customer_name, odt.created_at")
    .joins(" left join order_queue_stations as oqs on oqs.id = assigned_order_items.order_queue_station_id
              left join order_queue_process_by_zones as oqpz on oqpz.order_queue_station_id = oqs.id
              left join orders as od ON od.order_id = assigned_order_items.order_id
              left join order_items as odt ON odt.item_instance_code = assigned_order_items.instance_code AND odt.order_id = assigned_order_items.order_id
              left join customers as cus ON cus.customer_id = od.customer_id
              left join booking_orders as bo on bo.order_id = assigned_order_items.order_id
              left join bookings as bk on bk.booking_id = bo.booking_id
              left join dining_facilities as df on df.id = bk.dining_facility_id")
    .where("assigned_order_items.delivery_status = #{status} AND assigned_order_items.created_at >= '#{Time.now.beginning_of_day.utc}' #{oqs} #{table}")
    query = query.where("df.name LIKE ? OR odt.order_id LIKE ? OR odt.item_name LIKE ? OR cus.name = '#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%",)
    .order("assigned_order_items.assigned_order_item_id desc")
    .group("odt.order_items_id")

  end

  # Completed Order
  def completed_order(filter)
   query =  AssignedOrderItem.select("assigned_order_items.assigned_order_item_id, oqs.id as station_id, oqs.station_name, oqs.is_active, oqpz.zone_id, df.name as zone, df.type, odt.order_id, odt.item_code, odt.item_name, odt.price, odt.qty, odt.item_order_by, odt.options, odt.set_menu_items, cus.name as customer_name, odt.created_at")
    .joins(" left join order_queue_stations as oqs on oqs.id = assigned_order_items.order_queue_station_id
              left join order_queue_process_by_zones as oqpz on oqpz.order_queue_station_id = oqs.id
              left join orders as od ON od.order_id = assigned_order_items.order_id
              left join order_items as odt ON odt.item_instance_code = assigned_order_items.instance_code AND odt.order_id = assigned_order_items.order_id
              left join customers as cus ON cus.customer_id = od.customer_id
              left join booking_orders as bo on bo.order_id = assigned_order_items.order_id
              left join bookings as bk on bk.booking_id = bo.booking_id
              left join dining_facilities as df on df.id = bk.dining_facility_id")
    .where("assigned_order_items.delivery_status = true  AND assigned_order_items.created_at between '#{Time.now.beginning_of_day.utc}' and '#{Time.now.end_of_day.utc}'")
    query = query.where("df.name LIKE ? OR odt.order_id LIKE ? OR odt.item_name LIKE ? OR cus.name = '#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%",)
                 .group("assigned_order_items.order_id")
                 .limit(20)
                 .order("assigned_order_items.created_at")


     # completed_order = AssignedOrderItem.group(:order_id).where('delivery_status=true');
  end

  # def queue_items_count_query(status,filter) 
  #   query = AssignedOrderItem.select("count(odt.item_code) as total,oqs.id as station_id")
  #   .joins(" left join order_queue_stations as oqs on oqs.id = assigned_order_items.order_queue_station_id
  #             left join orders as od ON od.order_id = assigned_order_items.order_id
  #             left join order_items as odt ON odt.item_instance_code = assigned_order_items.instance_code AND odt.order_id = assigned_order_items.order_id
  #             left join customers as cus ON cus.customer_id = od.customer_id
  #             left join booking_orders as bo on bo.order_id = assigned_order_items.order_id
  #             left join bookings as bk on bk.booking_id = bo.booking_id
  #             left join dining_facilities as df on df.id = bk.dining_facility_id")
  #   .where("assigned_order_items.delivery_status = #{status} AND assigned_order_items.created_at >= '#{Time.now.beginning_of_day.utc}' ")
  #   query = query.where("df.name LIKE ? OR odt.order_id LIKE ? OR odt.item_name LIKE ? OR cus.name = '#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%",)
  #   .group("oqs.id")

  # end

  def queue_items_count_query(status,filter) 
    # query = OrderQueueStation.all
    query = OrderQueueStation.select("order_queue_stations.id as station_id,
                                  (case when (count(odt.item_code)>0) then count(odt.item_code) else 0 end) as total")
    .joins(" left join assigned_order_items as aoi on aoi.order_queue_station_id= order_queue_stations.id
              left join orders as od ON od.order_id = aoi.order_id
              left join order_items as odt ON odt.item_instance_code = aoi.instance_code AND odt.order_id = aoi.order_id
              left join customers as cus ON cus.customer_id = od.customer_id
              left join booking_orders as bo on bo.order_id = aoi.order_id
              left join bookings as bk on bk.booking_id = bo.booking_id
              left join dining_facilities as df on df.id = bk.dining_facility_id")
    .where("aoi.delivery_status = #{status} AND aoi.created_at >= '#{Time.now.beginning_of_day.utc}' ")
    query = query.where("df.name LIKE ? OR odt.order_id LIKE ? OR odt.item_name LIKE ? OR cus.name = '#{filter}'","%#{filter}%","%#{filter}%","%#{filter}%",)
    .group("order_queue_stations.id")
  end

end
