class Foodcourt::AddordersController < BaseFoodcourtController
  # before_action :set_dining, only: [:detail]

  def index
    @webview = false
    if check_mobile
      @webview = true
    end

    @tables = Table.all.active.order('zone_id asc').group("zone_id")
    @rooms = Room.all.active.order('zone_id asc').group("zone_id")
    @all_table = Table.all.active.order('status desc')
    @all_room = Room.all.active.order('status desc')
  end

  def detail
    @cashier_type = params[:type]
    @webview = false
    if check_mobile
      @webview = true
    end
    display_type = Lookup.find_by_lookup_type("display_type")
    if !display_type.nil? && display_type.value.to_i ==2
      @display_type = display_type.value
    else
      @display_type = nil
    end
    @menus    = []
    @menu     = []

    @table_id = params[:id]
    @table = DiningFacility.find(@table_id)
    @booking = @table.get_booking
    if @booking
      @booking_id = @booking.booking_id
      @obj_order = @booking.orders.first
      @customer = @obj_order.customer
      @date = @obj_order.created_at
      @order_items = @booking.order_items
    end
  end

  def get_menu_category ()
    if (params[:id])

      #Pull this menu
      @menu = MenuCategory.find_by_id(params[:id])

      # puts @menu.menu_items[1].item_attributes.to_json
      return @menu
    else
      MenuCategory.current_menu
    end
  end

  def get_item_instance
    @instance = MenuItemInstance.find(params[:id])
  end

  def get_menu()
    if (params[:id])
      #Pull this menu
      @menu = Menu.find_by_id(params[:id])
      @menu_category = MenuCategory.where("menu_id='#{@menu.id}'").order("order_by asc")
      # puts @menu.menu_items[1].item_attributes.to_json
      return @menu
    else
      Menu.current_menu
    end
  end

  def get_menu_sub_category ()

    id = params[:id]

    if (id)
      #Pull this menu
      @sub_menu = MenuCategory.where("menu_category_id = #{id}").active

      # puts @menu.menu_items[1].item_attributes.to_json
      return @sub_menu
    end
  end

  def get_all_product()
      @product = Product.all
  end

  def create
    if params[:booking_id].present?
      booking = Booking.find(params[:booking_id])
    end
    if params[:table_id].present?
      if booking.nil? || booking.dining_facility_id.to_i != params[:table_id].to_i
        table = DiningFacility.find(params[:table_id])
        booking = table.get_current_booking
      end
    end

    is_extra_time = false
    extra_time = ''

    items_arr = []
    JSON.parse(params[:order_items]).each { |i|
      i["item_instance_code"] = i["item_instance_code"].downcase.to_s
      if i["parent_order_item_id"];
        items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"parent_order_item_id": i["parent_order_item_id"],"options": JSON.parse(i["options"])}
      else
        items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"options": JSON.parse(i["options"])}
      end
      items_arr.push(items)
     }

    customer_id = params[:customer_id].present? ? params[:customer_id] : Customer.walkin.customer_id

    Order.transaction do
      @order = Order.new
      @order.source = params[:order_source]
      @order.order_type = params[:order_type]
      @order.customer_id = customer_id
      @order.items = items_arr
      @order.guest = params[:guest_info]
      @order.table_id = params[:table_id]  # this is dining facilities's id
      @order.new_booking = true
      @order.waiters = current_login_employee.name
      @order.employee_name = current_login_employee.name

      @order.is_extra_time = is_extra_time
      @order.extra_time    = extra_time

      if booking.nil? || booking.sale_id.present? || booking.booking_status == 'moved'
        @order.new_booking = true
      else
        @order.new_booking = false
        @order.booking_id = booking.booking_id
      end

      @status, @booking = @order.generate

      if @status && @booking
        #send order broadcast to order_channel
        if @order.table_id.to_i > 0
          table = DiningFacility.find(@booking.dining_facility_id)
          type  = 'order'
          from = getCloudDomain #get sub domain in cloud mode
          ActionCable.server.broadcast "order_channel",table: table,type:type,from:from
        end
      end

      if current_user.role != "waiter" && params[:create_type] == "create_pay"
        if @status && @booking && (@order.source == 'quick_service') || (@order.source == 'food_court')

          @status, @sale = Sale.request_bill(@order,current_user,current_login_employee)

          # for second display
          if @order.source == 'quick_service'
            from = getCloudDomain #get sub domain in cloud mode
            ActionCable.server.broadcast "second_display_channel",data: @sale,status:"sale",from:from
          end
          #end
        end
      end
    end
  end

  # render json for http status code
  def return_json_status_with_code(code, msg)
    render status: code, json: {
      message: msg,
      booking_id: booking_id
    }.to_json
  end

  def check_order_with_table(table_id)
    table =  DiningFacility.find(table_id)
    if table
       booking = table.get_current_booking
       # puts booking
       if booking
        if !booking.sale_id.nil?
          if booking.sale.sale_status == "completed" || booking.sale.sale_status == "new"
           @order.new_booking = true
           return false
          end
        else
           @order.new_booking = false
           @order.booking_id = booking.booking_id
           return false
         end
       end
    end
  end

  # this can always true
  def check_order_with_booking(booking)
    if booking.sale.sale_status == "completed" || booking.sale.sale_status == "new"
      @order.new_booking = true
      return false
    else
      @order.new_booking = false
      @order.booking_id = params[:booking_id]
      return false
    end
  end

  def process_order_queue(order_id,table_id,order_source)
    print_status = nil
    cup_status = nil

      #Send to background job for processing
      order        = Order.find(order_id)
      sidekiq      = Lookup.find_by_lookup_type("sidekiq")
      if ENV["SERVER_MODE"] != 'cloud'
        cup_status   = `#{"sudo service cups status"}`
        print_status = check_cup_status(cup_status)
      end

      if print_status
        if !sidekiq.nil?
          OrderQueueProcessorJob.perform_later(order_id, table_id)
        else
          if order
            oqs = OrderQueueStation.new
            oqs.process_order(order, table_id, order_source)
          end
          # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id)
          # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order
        end
      else
        if ENV["SERVER_MODE"] != 'cloud'
           cup_start    = `#{"sudo service cups start"}`
           cup_status   = `#{"sudo service cups status"}`
           print_status = check_cup_status(cup_status)
        end

        if print_status
          if !sidekiq.nil?
            OrderQueueProcessorJob.perform_later(order_id, table_id)
          else
            if order
              oqs = OrderQueueStation.new
              oqs.process_order(order, table_id, order_source)
            end
            # assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id)
            # ActionCable.server.broadcast "order_queue_station_channel",order: assign_order
          end
        else
          if ENV["SERVER_MODE"] != 'cloud'
              from = ""
            msg = ' Print Error ! Please contact to service'
            ActionCable.server.broadcast "call_waiter_channel",table: msg,time:'print_error',from:from
          end
          if !sidekiq.nil?
            OrderQueueProcessorJob.perform_later(order_id, table_id)
          else
            if order
                oqs = OrderQueueStation.new
                oqs.process_order(order, table_id, order_source)
            end

            from = getCloudDomain #get sub domain in cloud mode
            assign_order = AssignedOrderItem.assigned_order_item_by_job(order_id)
            ActionCable.server.broadcast "order_queue_station_channel",order: assign_order,from:from
          end
        end
      end
  end

  def check_cup_status(status)
    if status.include? "Active: active (running)" || "Active: active (exited)"   #"Cup Server is already running"
      return true
    end
    return false
  end

  #get cloud domain
  def getCloudDomain
    from = ""
    if ENV["SERVER_MODE"] == 'cloud'
      from = request.subdomain.to_s  + "." + request.domain.to_s
    end

    return from
  end
  def add_to_existing_order
    if params[:booking_id].present? && params[:sale_id].present?
      booking = Booking.find(params[:booking_id])
      saleobj =Sale.find(params[:sale_id])
      order =saleobj.orders[0]
      items_arr = []
      JSON.parse(params[:order_items]).each { |i|
        i["item_instance_code"] = i["item_instance_code"].downcase.to_s
         if i["item_instance_code"].include? "ext"
           is_extra_time = true
           arr_exts = i["item_instance_code"].split("_")
           if arr_exts[1].match(/^(\d)+$/)
            time = arr_exts[1].to_i*60*i["quantity"].to_i
            extra_time = Time.at(time)
           end
         end
         if i["parent_order_item_id"];
           items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"parent_order_item_id": i["parent_order_item_id"],"options": JSON.parse(i["options"])}
         else
          items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"options": JSON.parse(i["options"])}
         end
         items_arr.push(items)
       }
      order.items = items_arr
      order.new_booking = false
      order.booking_id = booking.booking_id
      @status, booking = order.generate
      order_array = []
      items_arr.each do |item|
        order_item =order.order_items.where("item_instance_code=?",item[:item_instance_code]).last
        saleobj.add_item (order_item)
        if !order_item.set_menu_items.nil?
          saleobj.add_sub_item(order_item.set_menu_items)
        end
      end
       # Re-compute for add
       saleobj.compute(order.source)
       saleobj.save
       order.save
       booking.save
       order_array.push(order.order_id)

      receipt_no = saleobj.receipt_no
      action_by = current_user.name
      type = "ADD_TO_EXISTING"

      remark = "#{action_by} add to existing order #{order_array} to Receipt No=>#{receipt_no}"
      sale_audit = SaleAudit.record_audit_sale(saleobj.sale_id,remark,action_by,type )
    end
    result = {:status=> @status}
    render :json => result.to_json
  end
end
