class Api::OrdersController <  Api::ApiController
   # skip_before_action  :authenticate
  #Description
  # This API show current order details
  # Input Params - order_id
  def show
      if params[:id]
        order = Order.find_by_order_id(params[:id])
        if order
          @order_items=order.order_items
        end
      end
  end

  def get_order
      order = Order.find(params[:order_id])
      order.order_items
  end

  # API - This api will retrive current booking for android with table or room id
  def view_orders
    booking_id = params[:booking_id]
    table_id = params[:table_id]
    if Booking.exists?(booking_id)
      booking = Booking.find(booking_id)

      if booking
        if booking.dining_facility_id.to_i == table_id.to_i
          if booking.booking_status == 'assign'
             if booking.sale_id.nil?
               @booking = booking
             end
          end
        else
          table = DiningFacility.find(table_id)
          @booking = table.get_booking
        end
      end
    else
      table = DiningFacility.find(table_id)
      @booking = table.get_booking
    end

    @tax_profile = TaxProfile.where("lower(group_type)='cashier'")
    # arr_tax = []

    # if !arr_tax.empty?
    #   @tax_profile = TaxProfile.where(:id => arr_tax)
    # else
    #   @tax_profile = TaxProfile.where("lower(group_type)='cashier'")
    # end

    #
    return current_shop.to_json
  end


  # Description
  # This API allow new order creation
  # Input Params
  # order_source [* default - emenu] | table_id | booking_id [table_booking_id & Room_booking_id] (*require for Dine-In) | order_type [* Default - Dine-in]
  # | guest_info (optional) | customer_id (* Default assigned to WALK-IN)
  # order_items {[item_code, item_instance_code , qty, option, variants]}
  # Output Params
  # Status [Success | Error | System Error] , order_id, error_message (*)
  def create
    Rails.logger.debug "Order Source - " + params[:order_source].to_s
    Rails.logger.debug "Table ID - " + params[:table_id].to_s

    current_shift = ShiftSale.current_shift
    if current_shift.nil?
      @status = false
      @message = "No Current Open Shift for This Employee"
    else
      if checkin_checkout_time(params[:booking_id])

        table = DiningFacility.find_by_name(params[:table_name]) if params[:table_name].present?
        # table = DiningFacility.find(params[:table_id]) if params[:table_id].present?

        booking = table.current_checkin_booking if table
        booking ||= Booking.find(params[:booking_id]) if params[:booking_id].present?

        #for extratime
        is_extra_time = false
        extra_time = ''
         items_arr = []
         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,"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,"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"options": i["options"]}
           end
           items_arr.push(items)
         }
        #end extra time
        Order.transaction do
          @order =Order.create(source: params[:order_source],
                                order_type: params[:order_type],
                                customer_id: params[:customer_id].present? ? params[:customer_id] : Customer.walkin.customer_id, # for no customer id from mobile
                                items: items_arr,
                                guest: params[:guest_info],
                                table_id: !table.nil? ? table.id : '',
                                new_booking: true,
                                waiters: @user.name,
                                employee_name: @user.name,
                                is_extra_time: is_extra_time,
                                extra_time: extra_time
                                )
          # begin

          @status, @booking = @order.generate

          if @status && @booking
              # Order.process_order_queue(@order.order_id,@order.table_id,@order.source)
              if @order.source == 'app'
                @status, @sale = Sale.request_bill(@order,@user,@user)
              end
          end
          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
      else
        @status  =false
        @message ="Checkout time is over!"
      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
       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
  # Description
  # This API - allow order to add new items to existing orders, does not allow you to remove confirm items
  # Update customer info, Guest Info
  # Input Params
  # order_id , order_items {[item_code, item_instance_code , qty, option, variants]}
  # def update

  # end

  def order_params
    params.permits(:order_source, :booking_id,:order_type,
                    :customer_id,:guest_info, :table_id, :room_id,
                    order_items: [:item_code, :qty, :option, :remark])
  end

  #checked checkin and checkout time
  def checkin_checkout_time(booking_id)
    status = true
    if booking_id.present?
      if booking = Booking.find(booking_id)
        if booking.checkout_at.present?
          if booking.checkout_at <= Time.current
            status = false
          end
        end
      end
    end
    return status
  end

  def update
    Rails.logger.debug "Booking ID - " + params[:booking_id].to_s
    if checkin_checkout_time(params[:booking_id])
      Rails.logger.debug "Order Item ID - " + params[:order_item_id].to_s

      order_items_id = params[:order_item_id]
      qty_weight = params[:quantity].to_f
      remarks = params[:remark]

      order_item = OrderItem.find(order_items_id)
      before_updated_qty = order_item.qty
      if qty_weight < order_item.qty.to_f
        order_item.item_order_by = current_login_employee.name
        order_item.qty = qty_weight
        order_item.remark = remarks
        order_item.save

        if ENV["SERVER_MODE"] != "cloud" #no print in cloud server
          # print
          assigned_item = AssignedOrderItem.find_by_instance_code_and_order_id(order_item.item_instance_code, order_item.order_id)
          assigned_items = nil
          if !assigned_item.nil?
            assigned_items = AssignedOrderItem.where("item_code='" + assigned_item.item_code + "' AND " + "order_id='" + assigned_item.order_id + "'")
          end

          if !assigned_items.nil?
            assigned_items.each do |assign_item|
              # order queue stations
              oqs = assign_item.order_queue_station

              printer = PrintSetting.all

              unique_code="OrderItemPdf"
              if !printer.empty?
                printer.each do |printer_setting|
                  if printer_setting.unique_code == 'OrderItemPdf'
                    unique_code="OrderItemPdf"
                  elsif printer_setting.unique_code == 'OrderItemSlimPdf'
                    unique_code="OrderItemSlimPdf"
                  elsif printer_setting.unique_code == 'OrderSetItemPdf'
                    unique_code="OrderSetItemPdf"
                  elsif printer_setting.unique_code == 'OrderItemSlimCustomisePdf'
                    unique_code="OrderItemSlimCustomisePdf"
                  elsif printer_setting.unique_code == 'OrderItemCustomisePdf'
                    unique_code="OrderItemCustomisePdf"
                  elsif printer_setting.unique_code == 'OrderSetItemCustomisePdf'
                    unique_code="OrderSetItemCustomisePdf"
                  end
                end
              end

              print_settings=PrintSetting.find_by_unique_code(unique_code)
              order_queue_printer= Printer::OrderQueuePrinter.new(print_settings)
              order_queue_printer.print_order_item(print_settings, oqs, order_item.order_id, order_items_id, print_status=" (Cancelled)", before_updated_qty )
            end
          end
        end

        return return_json_status_with_code(200, "updated successfully!")
      else
        return return_json_status_with_code(304, "Quantity is over!")
      end
    else
      return return_json_status_with_code(406, "Checkout time is over!")
    end
  end

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

    return from
  end
end
