class MenuItem < ApplicationRecord
  # before_create :generate_menu_item_code

  belongs_to :menu_category, :optional => true
  has_many :menu_item_instances
  has_many :commissions
  has_many :product_commissions

  # 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

  has_many :menu_item_sets
  has_many :item_sets, through: :menu_item_sets

  validates_presence_of :item_code, :name, :type, :min_qty,:account_id
  validates_uniqueness_of :item_code
  
  default_scope { order('item_code asc') }

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

  # Item Image Uploader
  mount_uploader :image_path, MenuItemImageUploader

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

  # Work with item_code = item_instance_code
  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("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

  # private

  # def generate_menu_item_code
  #   self.item_code = SeedGenerator.generate_code(self.class.name, "I")
  # end

end
