class Menu < ApplicationRecord
  has_many :menu_categories, dependent: :destroy

  validates_presence_of :name, :valid_days, :valid_time_from, :valid_time_to
  validates_format_of :valid_days, :with => /\A([0-7]{1}(,[0-7]{1})*)?\Z/i
  #Default Scope to pull the active version only
  default_scope { where(is_active: true).order("created_at desc") }

  def self.current_menu
    today = DateTime.now
    day_of_week = today.wday
    menus = Menu.where("is_active = true and '#{today.strftime("%H:%M")}' between TIME(valid_time_from) and TIME(valid_time_to)")
    current_menu = nil

    #Loop through the menu which is valid days - get the first menu out and return result
    menus.each do |menu|
      if menu.valid_days.include?(day_of_week.to_s)
        current_menu = menu
        break
      end
    end

    return current_menu
  end

  def self.destroyMenu(menu)
      cats = MenuCategory.where("menu_id=?",menu.id)
      cats.each do |cat|
        abc = MenuCategory.destroyCategory(cat)
      end 
      menu.destroy
      return false
  end
end
