class MenuItem < ApplicationRecord

  belongs_to :menu_category, :optional => true
  has_many :menu_item_instances
  belongs_to :parent, :class_name => "MenuItem", foreign_key: "menu_item_id", :optional => true
  has_many :children, :class_name => "MenuItem", foreign_key: "menu_item_id"
  belongs_to :account

  validates_presence_of :item_code, :name, :type, :min_qty, :taxable, :min_selectable_item, :max_selectable_item

  default_scope { order('item_code asc') }

  scope :simple_menu_item, -> { where(type: 'SimpleMenuItem') }
  scope :set_menu_item, -> { where(type: 'SetMenuItem') } 

  def self.collection
    MenuItem.select("id, name").map { |e| [e.name, e.id] }
  end


  def self.search_by_item_code(item_code)
    menu_item_hash = Hash.new
    mt_instance = MenuItemInstance.find_by_item_instance_code(item_code)
    if (!mt_instance.nil?)
      menu_item = MenuItem.find(mt_instance.menu_item_id)
      menu_item_hash[:type] = menu_item.type
      menu_item_hash[:account_id] = menu_item.account_id
      menu_item_hash[:item_code] = menu_item.item_code
      menu_item_hash[:item_instance_code] = mt_instance.item_instance_code
      menu_item_hash[:name] = menu_item.name.to_s + " - " + mt_instance.item_instance_name.to_s
      menu_item_hash[:alt_name] = menu_item.alt_name.to_s + " - " + mt_instance.item_instance_name.to_s
      menu_item_hash[:price] = mt_instance.price
      menu_item_hash[:promotion_price] = mt_instance.promotion_price
      menu_item_hash[:is_on_promotion] = mt_instance.is_on_promotion
      menu_item_hash[:is_available] = mt_instance.is_available
      menu_item_hash[:taxable] = menu_item.taxable

      return menu_item_hash
    end

    return nil
  end

  def self.deleteRecursive(menu_item)

    # find the sub menu item of current item
    sub_menu_items = MenuItem.where("menu_item_id=?",menu_item.id)
    if sub_menu_items.length != 0
      sub_menu_items.each do |subitem|    
        if deleteRecursive(subitem)
        end
      end
      # find the instances of current menu item
      instances = MenuItemInstance.where("menu_item_id=?",menu_item.id)
      instances.each do |instance|
        instance.destroy
      end 
      menu_item.destroy
      return true
    else
      instances = MenuItemInstance.where("menu_item_id=?",menu_item.id)
      instances.each do |instance|
        instance.destroy
      end 
      menu_item.destroy
      return false
    end

  end 
end
