class DiningFacility < ApplicationRecord
  belongs_to :zone
  has_many :in_juties
  has_one :dining_charge
  has_one :cashier_terminal_by_zone, foreign_key: "zone_id", primary_key: "zone_id"
  has_one :cashier_terminal, through: :cashier_terminal_by_zone
  has_one :current_shift, through: :cashier_terminal
  has_many :order_queue_process_by_zones, foreign_key: "zone_id", primary_key: "zone_id"
  has_many :order_queue_stations, -> { where(is_active: true) }, through: :order_queue_process_by_zones

  has_many :bookings
  has_many :current_bookings, -> { left_joins(:sale).assign.merge(Booking.unscoped.where(checkout_at: nil).or(Booking.merge(Sale.unscoped.where(sale_status: ['new', nil])))) }, class_name: "Booking"
  has_one  :current_checkin_booking, -> { left_joins(:sale).assign.where(sale_id: nil) }, class_name: "Booking"
  has_one  :current_checkout_booking, -> { left_joins(:sale).assign.where.not(checkout_at: nil).merge(Sale.unscoped.where(sale_status: 'new')) }, class_name: "Booking"
  has_one  :current_reserved_booking, -> { left_joins(:sale).assign.where.not(reserved_at: nil).merge(Sale.unscoped.where(sale_status: nil)) }, class_name: "Booking"

  has_many :current_bookings, -> { left_joins(:sale).assign.merge(Booking.unscoped.where(checkout_at: nil).or(Booking.merge(Sale.unscoped.where(sale_status: ['new', nil])))) }, class_name: "Booking"
  has_one  :current_checkin_booking, -> { left_joins(:sale).assign.where(sale_id: nil) }, class_name: "Booking"
  has_one  :current_checkout_booking, -> { left_joins(:sale).assign.where.not(checkout_at: nil).merge(Sale.unscoped.where(sale_status: 'new')) }, class_name: "Booking"
  has_one  :current_reserved_booking, -> { left_joins(:sale).assign.where.not(reserved_at: nil).merge(Sale.unscoped.where(sale_status: nil)) }, class_name: "Booking"

  TABLE_TYPE = "Table"
  ROOM_TYPE = "Room"

  default_scope { order('order_by asc') }

  scope :active, -> {where(is_active: true)}

  def make_available
    self.status = 'available'
    self.save
  end

  def make_occupied
    self.status = 'occupied'
    self.save
  end

  def get_booking
    booking = self.current_checkin_booking
    if booking
      if booking.dining_facility_id.to_i == self.id
        if booking.booking_status == 'assign'
          return booking
        end
      end
    end
  end

  def get_current_booking
    Booking.where(dining_facility_id: self.id, booking_status: 'assign', checkout_at: nil).first #and checkout_at is null
  end

  def get_checkout_booking
    booking = self.current_reserved_booking
    if booking
      lookup_checkout_time = Lookup.collection_of("checkout_alert_time")
      free_time_min = 0
      if !lookup_checkout_time.empty?
        now = Time.current
        lookup_checkout_time.each do |checkout_time|
          arr_time = checkout_time[0].split("-")
          start_time = Time.zone.parse(arr_time[0].strip).strftime("%H:%M%p")
          end_time = Time.zone.parse(arr_time[1].strip).strftime("%H:%M%p")
          if start_time <= now && now <= end_time
            free_time_min = checkout_time[1].to_i
          end
        end
      end

      now = Time.current
      hr = (now.strftime("%H").to_i).to_int
      min = (now.strftime("%M").to_i).to_int
      if !booking.checkout_at.nil?
        checkout_at = booking.checkout_at
        checkout_at_hr = (checkout_at.strftime("%H").to_i).to_int
        checkout_at_min = (checkout_at.strftime("%M").to_i).to_int
        checkout_at_min -= min
        if (checkout_at_hr < hr)
          return booking
        elsif (checkout_at_hr == hr && checkout_at_min <= free_time_min)
          return booking
        else
          return nil
        end
      else
        return nil
      end
    end
  end

  def self.get_checkin_booking
    bookings = self.current_checkin_booking
    arr_booking = Array.new
    if bookings
      lookup_checkout_time = Lookup.collection_of("checkout_alert_time")
      free_time_min = 0
      if !lookup_checkout_time.empty?
        now = Time.current
        lookup_checkout_time.each do |checkout_time|
          arr_time = checkout_time[0].split("-")
          start_time = Time.zone.parse(arr_time[0].strip).utc.strftime("%H:%M%p")
          end_time = Time.zone.parse(arr_time[1].strip).utc.strftime("%H:%M%p")
          if start_time <= now && now <= end_time
            free_time_min = checkout_time[1].to_i
          end
        end
      end

      bookings.each do |booking|
        now = Time.current
        hr = (now.strftime("%H").to_i).to_int
        min = (now.strftime("%M").to_i).to_int
        if !booking.checkout_at.nil?
          checkout_at = booking.checkout_at
          checkout_at_hr = (checkout_at.strftime("%H").to_i).to_int
          checkout_at_min = (checkout_at.strftime("%M").to_i).to_int
          checkout_at_min -= min
          if (checkout_at_hr < hr)
            arr_booking.push({'table_id' => booking.dining_facility_id})
          elsif (checkout_at_hr == hr && checkout_at_min <= free_time_min)
            arr_booking.push({'table_id' => booking.dining_facility_id})
          end
        end
      end
    end
    return arr_booking
  end

  #send order items and send to order queue
  def self.check_in_booking(table_id)
    table = DiningFacility.find(table_id)
    #Send to background job for processing
    # CheckInBookingJob.perform_later(table)
     #if ENV["SERVER_MODE"] != 'cloud'
     if ENV["SERVER_MODE"] == 'cloud'
        from = request.subdomain  + "." + request.domain
      else
        from = ""
      end
      ActionCable.server.broadcast "check_in_booking_channel",table: table,from:from
    #end
  end

  def self.checkin_time
    table = DiningFacility.get_checkin_booking
    if table.length > 0
      if ENV["SERVER_MODE"] == 'cloud'
        from = request.subdomain  + "." + request.domain
      else
        from = ""
      end
      if ENV["SERVER_MODE"] != 'cloud'
        ActionCable.server.broadcast "checkin_channel",table: table,from:from
      end
    end
  end

  def check_time(time, booking = nil, type)
    status = true
    today = Time.current.utc.strftime("%Y-%m-%d %H:%M")
    check_time = time.utc.strftime("%Y-%m-%d %H:%M")
    if type.downcase == "checkin"
      if check_time < today
        status = false
      end
    else
      if !booking.nil?
        checkin_at = booking.checkin_at.utc.strftime("%Y-%m-%d %H:%M")
        if check_time <= checkin_at
          status = false
        end
      end
    end
    return status
  end

end
